MongoDB: Query an Array of Documents

Felt that it wasn’t very apparent how to do to do a query of array of objects (documents). Maybe because I used the wrong terminology when searching. I searched an array of object as oppose to array of documents.

{
    "firstName": "joe",
    "lastName": "smith",
    "products": [
        {
            "title": "The Power of Habit",
            "isbn10": "081298160X"
        },
        {
            "title": "The Intelligent Investor",
            "isbn10": "0060555661"
        }
    ],
    "tags": [
        "investing",
        "habit"
    ]
}
{
    "firstName": "jane",
    "lastName": "doe",
    "products": [
        {
            "title": "Divergent",
            "isbn10": "9780062024039"
        },
        {
            "title": "Wonder",
            "isbn10": "9780375869020"
        }
    ],
    "tags": [
        "teen"
    ]
}

To search for tags

db.[COLLECTION].find( {[FIELD]: "[SEARCHTERM]"} )
db.users.find( {tags: "teen"} )

To search for product title:

db.[COLLECTION].find( {[OUTERFIELD]: { $elemMatch: { [INNERFIELD]: "[SEARCHTERM]" } } } )
db.users.find( {products: { $elemMatch: { title: "Divergent" } } } )

Regular expression search

db.[COLLECTION].find( {[OUTERFIELD]: { $elemMatch: { [INNERFIELD]: { $regex: '[SEARCHTERM]', $options: 'i' } } } } )
db.users.find( {products: { $elemMatch: { title: { $regex: 'int', $options: 'i' } } } } )

returns 1st document with Intelligent Investor as title

Try it out from command line:
mongo ds039507.mongolab.com:39507/wishlist -u mfcoding -p password
db.users.find( {tags: "teen"} )
db.users.find( {products: { $elemMatch: { title: "Divergent" } } } )
db.users.find( {products: { $elemMatch: { title: { $regex: 'int', $options: 'i' } } } } )

Advertisements
This entry was posted in MongoDB and tagged , , , , . Bookmark the permalink.

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