<CharlieDigital/> Programming, Politics, and uhh…pineapples

23Aug/11Off

Filtering By “Reaching” Into Arrays With Mongo

One seriously neat capability with Mongo is the ability to filter by "reaching" into an array and filtering on a property of an object in an array.

This is seriously powerful stuff and incredibly easy with Mongo.  There's an example in the official SDK docs, but it's buried pretty deeply in there.

So here's a short summary. Say we are building an address book.

From the Mongo shell, we would enter:

> use addressbook
switched to db addressbook

To create the "addressbook" repository.

Next, we insert two contacts:

> db.contacts.insert({
... Name: "John",
... Addresses: [
...             {Street: "3 Main St.", Town: "Princeton", State: "NJ"},
...             {Street: "198 5th Ave.", Town: "New York", State: "NY"}
...     ]
... })
> db.contacts.insert({
... Name: "Christy",
... Addresses: [
...             {Street: "47 Park Ave.", Town: "New York", State: "NY"}
...     ]
... })

So what if we want to find the list of all contacts who have an address in the state "NY"?

In Mongo, this can be accomplished with the following query:

> db.contacts.find({ "Addresses.State" : "NY" } , { Name: 1 })
{ "_id" : ObjectId("4e54148fdf15eca8a7d2e6d5"), "Name" : "John" }
{ "_id" : ObjectId("4e5414b5df15eca8a7d2e6d6"), "Name" : "Christy" }

Love that simplicity.

Posted by Charles Chen

Filed under: Mongo Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.