Mongo – Querying documents within documents

Some of our collections in Mongo are built with embedded documents, This means the actual raw data is held in the following heirarchy:

OurMongoDB (DB)
OurMongoCollection (Collection)
                                _id          (document)
                                Car         (document)
                                                _id                       (embedded document)
                                                Channel             (embedded document)
                                                Make                   (embedded document)
                                                Model                  (embedded document)
                                                …
                                userId   (document)

This means that normal mongo db find statements will not work if you are searching based on criteria…

To search for embedded document data – use dot notation (http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29

--return only where channel is Test1
db.ourMongoCollection.find({"car.channel" : "Test1"});

--return only where channel is Test2
db.ourMongoCollection.find({"car.channel" : "Test2"});

--return count of all documents with channel as Test2
db.ourMongoCollection.find({"car.channel" : "Test2"}).count();

--return count of all channel Test1 documents with a make of Honda 
--(search criteria is case sensitive)
db.ourMongoCollection.find({"car.channel" : "Test1", "car.make" : "HONDA"}).count();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: