28

I have the following document structure:

{
   "_id":"12345",
   "value":{
      "T":0,
      "v":[
         {
            "name":"JW",
            "cost":100
         }
      ]
   }
}

How do I query the name key? I tried the dot notation but without luck (I think it works for only two levels)

1
  • If you were by any chance doing a group by, you then need to use the $unwind operation on the value.v key before you can operate on the name/cost fields. Commented Jan 6, 2017 at 20:35

2 Answers 2

38

It's not clear exactly what you tried, but this should work to find the above doc by name:

db.collection.find({ "value.v.name": "JW" })

Reference

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, i'm sure it did not work for me, maybe i got the query wrong.
I don't think you can use the dot operator on an array.
@SamuelO'Malley I just updated the Reference link that better shows that this is supported with arrays.
20

You should use $elemMatch operator:

db.collection.find({
    'value.v': { 
        $elemMatch: {
            name: 'JW', // "name == 'JW'"
            cost : 100 //if you need "&& cost == 100"
        }
    }
});

Mongo docs

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.