Skip to content

Instantly share code, notes, and snippets.

@shannonbradshaw
Last active August 1, 2016 12:19
Show Gist options
  • Save shannonbradshaw/5465f076462ea4e891f71a7c05f652ea to your computer and use it in GitHub Desktop.
Save shannonbradshaw/5465f076462ea4e891f71a7c05f652ea to your computer and use it in GitHub Desktop.
Task: Queried Element in an Array

Suppose you have a collection called figures containing the following documents.

{
    "_id" : 1
    "shapes" : [
        { "shape": "square", "color": "blue" },
        { "shape": "circle", "color": "red" }
    ]
}

{
    "_id" : 2
    "shapes" : [
        { "shape": "triangle", "color": "black" },
        { "shape": "square", "color": "orange" }
    ]
}

The following query:

db.test.find({"shapes.color": "red"}, {"shapes.shape": 1, "_id": 0})

or this query:

db.test.find({shapes: {"$elemMatch": {color: "red"}}},
             {"shapes.shape": 1, "_id": 0})

will return the first document in the collection, but always with ALL array items in shapes.

{
    "shapes": [
        {"shape": "square"},
        {"shape": "circle"}
    ]
}

Write a query that will return only the array item that matched the query in the shapes array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment