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.

5

1 Answer 1

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 .

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

1 Comment

Awesome. In that case, @cherhan would you mind up voting the answer. ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.