MongoDB (3.2+) の最新バージョンでは、$filter
演算子を使用して、指定された条件に基づいて返す配列フィールドのサブセットを選択できます。返される要素は、フィールド配列からの元の順序になります。
mongo
シェルでの例:
db.items.aggregate([
{ $match : {
_id: 5
}},
{ $project: {
items: {
$filter: {
input: "$items",
cond: {
"$in": ["$$this", [1, 9, 4]]
}
}
}
}
}])
注: この質問の元の配列には値が4
2 回あるため、$filter
コマンドは両方の出現を返します。
{ "_id" : 5, "items" : [ 1, 4, 9, 4 ] }
一意の一致するアイテムのみを返す代替アプローチの場合、$setIntersection
演算子を使用できます。
db.items.aggregate([
{ $match : {
_id: 5
}},
{ $project: {
items: {
$setIntersection: ['$items', [1,4,9]]
}
}}
])
これは以下を返します: { "_id" : 5, "items" : [ 1, 4, 9 ] }
.
(2012 年 9 月の元の回答を以下に示します)
ドキュメント操作をサーバー側で行いたい場合は、MongoDB 2.2のAggregation Frameworkを使用できます。
db.items.aggregate(
// Match the document(s) of interest
{ $match : {
_id: 5
}},
// Separate the items array into a stream of documents
{ $unwind : "$items" },
// Filter the array
{ $match : {
items: { $in: [1, 9, 4] }
}},
// Group the results back into a result document
{ $group : {
_id: "$_id",
items: { $addToSet : "$items" }
}}
)
結果:
{
"result" : [
{
"_id" : 5,
"items" : [
9,
4,
1
]
}
],
"ok" : 1
}