Reputation: 2527
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.
Upvotes: 1
Views: 413
Reputation: 3932
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 .
Upvotes: 1