Dot Notation To Access Sub Document: MongoDB

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.

> use nesting
switched to db nesting

> db.users.insert({"name": "Satish", 
                   "email": {"work": "technotip.community@gmail.com", 
                   "personal": "satish@technotip.org"}});
WriteResult({ "nInserted" : 1 })

> db.users.find().pretty()
{
        "_id" : ObjectId("53bfc9f54ed48cddc53effa8"),
        "name" : "Satish",
        "email" : {
                "work" : "technotip.community@gmail.com",
                "personal" : "satish@technotip.org"
        }
}

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

> db.users.find({"email": {"work": "technotip.community@gmail.com", 
                                   "personal": "satish@technotip.org"}});
{ "_id" : ObjectId("53bfc9f54ed48cddc53effa8"), 
  "name" : "Satish", 
  "email" : { "work" : "technotip.community@gmail.com", 
              "personal" : "satish@technotip.org" } 
}

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

> db.users.find({"email": {"work": "technotip.community@gmail.com"}});
> db.users.find({"email": {"personal": "satish@technotip.org", 
                           "work": "technotip.community@gmail.com"}});

Finding document with dot notation

> db.users.find({"email.work": "technotip.community@gmail.com"});
{ "_id" : ObjectId("53bfc9f54ed48cddc53effa8"), 
  "name" : "Satish", 
  "email" : { "work" : "technotip.community@gmail.com", 
              "personal" : "satish@technotip.org" } }

Using dot notation is the best way to access sub-document or sub-object in MongoDB.