Предположим, у вас есть следующие документы в моей коллекции:
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"shapes":[
{
"shape":"square",
"color":"blue"
},
{
"shape":"circle",
"color":"red"
}
]
},
{
"_id":ObjectId("562e7c594c12942f08fe4193"),
"shapes":[
{
"shape":"square",
"color":"black"
},
{
"shape":"circle",
"color":"green"
}
]
}
Выполнить запрос:
db.test.find({"shapes.color": "red"}, {"shapes.color": 1})
Или
db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})
Возвращает соответствующий документ (Документ 1) , но всегда со ВСЕМИ элементами массива в формах
:
{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
Однако я хотел бы получить документ (Документ 1) только с массивом, содержащим color = red
:
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
Как я могу это сделать?