1

I have a collection with document structure as below:

"_id": {
    "userId": "user_id_1"
},
"val": {
    "status": 1,
    "otherKey": "otherValue"
}

There are two queries I tried to get this document:

db.getCollection('my_collection').find({ "_id" : { "userId" : "user_id_1"} , "val.status" : 1})

and

db.getCollection('my_collection').find({ "_id" : { "userId" : "user_id_1"} , "val" : { "status" : 1}})

The first query returns the document while the second doesn't. I am tying to match status in similar way as I did for the user id. Can someone explain me the difference between the two queries?

2 Answers 2

1

this assertion "val": { "status" : 1} in the query means : return the documents where val equals the JSON object {"status": 1}

Here i'ts not the case because the val object also has the otherKey field

To retrieve it with this syntax, you should use

db.getCollection('my_collection').find(
 { "_id" : { "userId" : "user_id_1"} ,
   "val" : { "status" : 1, "otherKey": "otherValue" }}
)
Sign up to request clarification or add additional context in comments.

Comments

1

When you query an embedded document and write the query (i.e. second query) as mentioned in OP, the MongoDB matches the embedded document exactly including the order of the fields.

db.getCollection('my_collection').find({ "_id" : { "userId" : "user_id_1"} , "val" : { "status" : 1}})

If you write the query changing the order of the fields (i.e. status and otherKey), you may not get the result as MongoDB matches the embedded document exactly (i.e. identical match including the order of the fields).

db.getCollection('my_collection').find(
 { "_id" : { "userId" : "user_id_1"} ,
   "val" : {"otherKey": "otherValue",  "status" : 1 }}
)

MongoDB works differently for Dot Notation (i.e. your first query in the OP). It doesn't perform exact match as described above. It just looks for the field mentioned in the query.

Query by status:-

db.getCollection('my_collection').find({ "_id" : { "userId" : "user_id_1"} , "val.status" : 1})

Query by otherKey:-

db.getCollection('my_collection').find({ "_id" : { "userId" : "user_id_1"} , "val.otherKey" : "otherValue"})

Conclusion:-

Query by dot notation is better if you don't want to query by all the fields in the embedded document.

Comments

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.