1

I have a collection (users) which looks very much the same as mentioned below.

db.users.find().pretty();
{
        "_id" : ObjectId("5773fc2826e0b6cf532569ca"),
        "user" : {
                "login" : "tester"
        }
}
{
        "_id" : ObjectId("5773fd6426e0b6cf532569cb"),
        "user" : {
                "login" : "tester",
                "name" : "anil"
        }
}

When I do

> db.users.find({"user":{"login":"tester"}});

I get this as the result

{ "_id" : ObjectId("5773fc2826e0b6cf532569ca"), "user" : { "login" : "tester" } }

However when I do below, I get no records.

db.users.find({"user":{"name":"anil"}});

> so my question is why does the second query returns no response ?

Also, based on the examples above, I am even doubting if this is the correct way to access subdocuments ?

Shouldn't the subdocuments be accessed via .notation. Something like below ? (in which case I get the correct output in both the cases)

db.users.find({"user.login":"tester"});
{ "_id" : ObjectId("5773fc2826e0b6cf532569ca"), "user" : { "login" : "tester" } }
{ "_id" : ObjectId("5773fd6426e0b6cf532569cb"), "user" : { "login" : "tester", "name" : "anil" } }

and

> db.users.find({"user.name":"anil"});
{ "_id" : ObjectId("5773fd6426e0b6cf532569cb"), "user" : { "login" : "tester", "name" : "anil" } }
>

1 Answer 1

4

Also, based on the examples above, I am even doubting if this is the correct way to access subdocuments ?

This is not actually. The first query, db.users.find({"user":{"login":"tester"}});, means that you're looking for a user that equals to {"login":"tester"} object completely, not a user with login field equals to tester. There is one document that matches with that criteria and that document actually returned as the query result.

Likewise, the second query, db.users.find({"user":{"name":"anil"}});, means that you're looking for a user that equals to {"name":"anil"} object completely. There is no such user. There is one document that matches with your query partially but it's not enough.

If you're looking for a user with name equals to anil, use Dot Notation to access the sub-document, as you did in your second group of queries.

Shouldn't the subdocuments be accessed via .notation. Something like below ? (in which case I get the correct output in both the cases)

Yes. this is the correct way.

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

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.