Today lets see how we can access sub-document or sub-object using Dot notation, in MongoDB.
Documents in our collection
nesting database, users collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | > use nesting
switched to db nesting
> db.users.insert({"name": "Satish",
"email": {"work": "[email protected]",
"personal": "[email protected]"}});
WriteResult({ "nInserted" : 1 })
> db.users.find().pretty()
{
"_id" : ObjectId("53bfc9f54ed48cddc53effa8"),
"name" : "Satish",
"email" : {
"work" : "[email protected]",
"personal" : "[email protected]"
}
} |
Here we have a sub-document called “email” – with work and personal keys.
Dot Notation To Access Sub Object: MongoDB
YouTube Link: https://www.youtube.com/watch?v=mqB_ilUXg1o [Watch the Video In Full Screen.]
Finding document using sub-object
1 2 3 4 5 6 7 | > db.users.find({"email": {"work": "[email protected]",
"personal": "[email protected]"}});
{ "_id" : ObjectId("53bfc9f54ed48cddc53effa8"),
"name" : "Satish",
"email" : { "work" : "[email protected]",
"personal" : "[email protected]" }
} |
But if the order of fields is changed it doesn’t retrieve the document, as it does not match the BSON bytes stored in the database.
Finding document using sub-object: Does not work
1 2 3 | > db.users.find({"email": {"work": "[email protected]"}});
> db.users.find({"email": {"personal": "[email protected]",
"work": "[email protected]"}}); |
Finding document with dot notation
1 2 3 4 5 | > db.users.find({"email.work": "[email protected]"});
{ "_id" : ObjectId("53bfc9f54ed48cddc53effa8"),
"name" : "Satish",
"email" : { "work" : "[email protected]",
"personal" : "[email protected]" } } |
Using dot notation is the best way to access sub-document or sub-object in MongoDB.