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)

CDspace
  • 2,639
  • 18
  • 30
  • 36
karel lahmy
  • 397
  • 1
  • 5
  • 15
  • 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. – AP. Jan 06 '17 at 20:35

2 Answers2

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

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
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

AP.
  • 8,082
  • 2
  • 24
  • 33
neftedollar
  • 1,108
  • 10
  • 14