Dot Notation (Reaching into Objects)

MongoDB is designed for store JSON-style objects.  The database understands the structure of these objects and can reach into them to evaluate query expressions.

Let's suppose we have some objects of the form:

> db.persons.findOne()
{ name: "Joe", address: { city: "San Francisco", state: "CA" } ,
  likes: [ 'scuba', 'math', 'literature' ] }

Querying on a top-level field is straightforward enough using Mongo's JSON-style query objects:

> db.persons.find( { name : "Joe" } )

But what about when we need to reach into embedded objects and arrays?  This involves a bit different way of thinking about queries than one would do in a traditional relational DBMS.  To reach into embedded objects, we use a "dot notation":

> db.persons.find( { "address.state" : "CA" } )

Reaching into arrays is implicit: if the field being queried is an array, the database automatically assumes the caller intends to look for a value within the array:

> db.persons.find( { likes : "math" } )

We can mix these styles too, as in this more complex example:

> db.blogposts.findOne()
{ title : "My First Post", author: "Jane",
  comments : [{ by: "Abe", text: "First" },
              { by : "Ada", text : "Good post" } ]
}
> db.blogposts.find( { "comments.by" : "Ada" } )

We can also create indexes of keys on these fields:

db.persons.ensureIndex( { "address.state" : 1 } );
db.blogposts.ensureIndex( { "comments.by" : 1 } );

Dot Notation vs. Subobjects

Suppose there is an author id, as well as name. To store the author field, we can use an object:

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

If we want to find any authors named Jane, we use the notation above:

> db.blog.findOne({"author.name" : "Jane"})

To match only objects with these exact keys and values, we use an object:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

Note that

db.blog.findOne({"author" : {"name" : "Jane"}})

will not match, as subobjects have to match exactly (it would match an object with one field: {"name" : "Jane"}).

Array Element by Position

Array elements also may be accessed by specific array position:

// i.e. comments[0].by == "Abe"
> db.blogposts.find( { "comments.0.by" : "Abe" } )

(The above examples use the mongo shell's Javascript syntax.  The same operations can be done in any language for which Mongo has a driver available.)


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

IF YOU HAVE A QUESTION, POST IT TO THE USER GROUP.

These pages are fine for comments, but for questions, your best bet will always be the MongoDB User Group.

blog comments powered by Disqus