1

I have a db like this

{
    "name": "Tom",
    "cars": [
        {
            "name": "Shirley",
            "kind": "Bugatti"
        },
        {
            "name": "Jessica",
            "kind": "Maserati"
        },      
    ]
}

I have a query like this

db.people.findOne({"name: "Tom"});

I just want to return the object where "name": "Jessica"

{
    "name": "Jessica",
    "kind": "Maserati"
}

How can I do this?

I tried

db.people.findOne({"name": "Tom"}, {"cars.name": 1});
db.people.findOne({"name": "Tom"}, {"cars.name.Jessica": 1});

I'm trying to prevent returning the whole thing then sorting everything after.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • Which object are you trying to get to? The second one? The last one? First one alphabetically by name? The "Jessica" object meets several criteria and you didn't spell out what criteria you are searching for. – Brandon Oct 20 '13 at 21:50
  • Just trying to pluck one object via "name". – ThomasReggi Oct 20 '13 at 21:51
  • The first object in the query is your filter and the second object is the list of fields to return. You are mixing them. – Brandon Oct 20 '13 at 21:52
  • No I'm not. they query is adequate. I'm trying to trim down the fields so that I just return that one object. Attaching a more specific query is still going to give me the whole doc. – ThomasReggi Oct 20 '13 at 21:55

1 Answers1

1
db.people.findOne({"name": "Tom"}, {"cars": { $elemMatch : { "name": "Jessica"}}});

{
    "_id" : ObjectId("526453188257d12214ea287d"),
    "cars" : [
        {
            "name" : "Jessica",
            "kind" : "Maserati"
        }
    ]
}
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424