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.