[SERVER-8834] MongoDB return fields from subdocuments in an array Created: 03/Mar/13  Updated: 08/Mar/13  Resolved: 05/Mar/13

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Question Priority: Minor - P4
Reporter: Kurt Agius Assignee: Ian Whalen (Inactive)
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Participants:

 Description   

I have a document such as:

{_id: ObjectId("512fe1e5b9912a714eef4e54"),
items: [

{type:'test', name:'my first object'}

,

{type:'test', name:'my second object'}

]}

Basically i need to list all the names in my items array something similar to:

db.log.findOne({_id:ObjectId("512fe1e5b9912a714eef4e54")},{'items.$':{name:1}});

Is there another way to do it ? Or is it even planned/discussed somewhere ?



 Comments   
Comment by Kurt Agius [ 05/Mar/13 ]

Works perfect, thanks

Comment by Ian Whalen (Inactive) [ 04/Mar/13 ]

Kurt, without more specifics about your desired output, it sounds like this should work for you if you're on 2.2.x or later and can use the aggregation framework:

db.log.aggregate(
  { $match   : { _id : ObjectId("512fe1e5b9912a714eef4e54") }},
  { $project : { a : "$items.name", "_id" : 0 }}
)

which will output this:

{
  "result": [
    {
      "a": [
        "my first object",
        "my second object"
      ]
    }
  ],
  "ok": 1
}

or were you looking for something different?

Generated at Thu Feb 08 03:18:35 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.