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:
1 2 |
> use addressbook switched to db addressbook |
To create the “addressbook” repository.
Next, we insert two contacts:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
> 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:
1 2 3 |
> db.contacts.find({ "Addresses.State" : "NY" } , { Name: 1 }) { "_id" : ObjectId("4e54148fdf15eca8a7d2e6d5"), "Name" : "John" } { "_id" : ObjectId("4e5414b5df15eca8a7d2e6d6"), "Name" : "Christy" } |
Love that simplicity.