1

My MongoDB has a key-value pair structure, inside my document has a data field which is an array that contains many subdocuments of two fields: name and value.

How do I search for a subdocument e.g ( {"name":"position", "value":"manager"}) and also multiple (e.g. {"name":"age", "value" : {$ge: 30}})

EDIT: I am not looking for a specific subdocument as I mentioned in title (not positional reference), rather, I want to retrieve the entire document but I need it to match the two subdocuments exactly.

drhanlau
  • 2,517
  • 2
  • 24
  • 42
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – s7vr Apr 27 '17 at 13:53
  • No, I don't want to find a specific subdocument, I want to retrieve the entire record. But my question is how do I query using a subdocument in an array. – drhanlau Apr 27 '17 at 13:56
  • 1
    Understood. Use `$elemMatch` query variant. https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ & https://docs.mongodb.com/manual/tutorial/query-array-of-documents/ – s7vr Apr 27 '17 at 13:57
  • Thanks @Veeram, is there any example if I want to query multiple elemMatch, is it using $and operator? – drhanlau Apr 27 '17 at 14:03
  • Np. Here you go. https://docs.mongodb.com/manual/reference/operator/query/all/#use-all-with-elemmatch – s7vr Apr 27 '17 at 14:05

1 Answers1

1

Here are 2 queries to find the following record:

{ 
    "_id" : ObjectId("sometobjectID"), 
    "data" : [
        {
            "name" : "position", 
            "value" : "manager"
        }
    ]
}

// Both value and name (in the same record):
db.demo.find({$elemMatch: {"value": "manager", "name":"position"}})


// Both value and name (not necessarily in the same record):
db.demo.find({"data.value": "manager", "data.name":"position"})


// Just value:    
db.demo.find({"data.value": "manager"})

Note how the . is used, this works for all subdocuments, even if they are in an array.

You can use any operator you like here, including $gte

edit

$elemMatch added to answer because of @Veeram's response

This answer explains the difference between $elemMatch and .

Community
  • 1
  • 1
Dan Green-Leipciger
  • 3,776
  • 1
  • 19
  • 29