私のコレクションに次のドキュメントがあるとします。
{
"_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
ます:
{ "shapes":
[
{"shape": "square", "color": "blue"},
{"shape": "circle", "color": "red"}
]
}
ただし、以下を含む配列のみを使用してドキュメント(ドキュメント1)を取得したいと思いますcolor=red
。
{ "shapes":
[
{"shape": "circle", "color": "red"}
]
}
これどうやってするの?
MongoDB 2.2の新しい$elemMatch
射影演算子は、最初に一致したshapes
要素のみを含むように返されるドキュメントを変更する別の方法を提供します。
db.test.find(
{"shapes.color": "red"},
{_id: 0, shapes: {$elemMatch: {color: "red"}}});
戻り値:
{"shapes" : [{"shape": "circle", "color": "red"}]}
2.2$ projection operator
では、を使用してこれを行うこともできます。ここ$
で、プロジェクションオブジェクトのフィールド名は、クエリからのフィールドの最初の一致する配列要素のインデックスを表します。以下は、上記と同じ結果を返します。
db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});
MongoDB3.2アップデート
3.2リリース以降、新しい$filter
集計演算子を使用して、射影中に配列をフィルタリングできます。これには、最初の一致だけでなく、すべての一致を含めるという利点があります。
db.test.aggregate([
// Get just the docs that contain a shapes element where color is 'red'
{$match: {'shapes.color': 'red'}},
{$project: {
shapes: {$filter: {
input: '$shapes',
as: 'shape',
cond: {$eq: ['$$shape.color', 'red']}
}},
_id: 0
}}
])
結果:
[
{
"shapes" : [
{
"shape" : "circle",
"color" : "red"
}
]
}
]
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加