Dot Notation To Access Sub Document: MongoDB

Advertisement:

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


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://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": "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

1
2
3
> 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

1
2
3
4
5
> 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.

Advertisements

1 thought on “Dot Notation To Access Sub Document: MongoDB”

Leave a Reply

Your email address will not be published. Required fields are marked *