user641887
user641887

Reputation: 1586

mongodb accessing subdocuments

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" } }
>

Upvotes: 1

Views: 1802

Answers (1)

Ali Dehghani
Ali Dehghani

Reputation: 48203

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.

Upvotes: 4

Related Questions