![](/img/trans.png)
[英]How do I update Array Elements matching criteria in a MongoDB document?
[英]How to return elements of array matching criteria in MongoDB
我是 mongodb 的新手,我仍在努力解決問題,所以如果我的問題太簡單或已在其他地方得到解答,請原諒我。
我有一個像下面這樣的集合
[
{"_id":1,
"data" :[{"a":1,"b":2},{"a":1,"b":3},{"a":2,"b":3},{"a":4,"b":1}]
},
{"_id":2,
"data" :[{"a":3,"b":2},{"a":2,"b":4},{"a":5,"b":3},{"a":7,"b":1}]
}
]
如何編寫一個查詢來查看第一個文檔的數據數組並返回“a”等於一個的所有元素。
像這樣的東西是預期的 output:
[{"a":1,"b":2},{"a":1,"b":3}]
這是我目前的嘗試
db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}})
但這給了我
{"_id": 1, "data":
[{"a":1,"b":2},{"a":1,"b":3}]
}
除了“數據”中的結果之外,我不需要或想要任何東西。
有人可以幫幫我嗎?
我也很感激任何用於在文檔中篩選數組以查找與單個文檔上更一般條件匹配的元素的指針(即,對於上面的示例,查找 a+b < 5、a > b、a>1 和 b 的文檔>2、a >3 或 b<1 等)
編輯:我正在使用 mongodb 版本 4.2.6
你幾乎擁有一切,你只是忘記了最后的投影:
db.myCollection.find({_id:1},{data: {$elemMatch: {a : 1}}}, {_id: 0, data: 1})
$filter
是在文檔中過濾 arrays 的通用方法。 擴展您的輸入集以提供更多上下文和多樣性:
var r =
[
{
"_id": 0,
"other":6,
"data" :[{"a":1,"b":2,"c":"X"},
{"a":1,"b":3,"c":"Y"},
{"a":2,"b":3,"c":"Q"},
{"a":4,"b":1,"c":"Z"}]
},
{
"_id": 1,
"other":7,
"data" :[{"a":1,"b":2,"c":"A"},
{"a":1,"b":3,"c":"B"},
{"a":7,"b":7,"c":"C"},
{"a":1,"b":8,"c":"D"}]
}
];
db.foo.insert(r);
然后這兩個管道演示了$filter
的多功能性:
c = db.foo.aggregate([
{$project: {_id:false,
// Notice input is $data and output project is data; this
// means overwrite the old data array with the filtered array.
// Also: The double dollar is how we reference the "as"
// variable. Single dollar variables refer to the fields
// of the incoming doc; we show how to use $other in this
// example. $other remains constant for the doc as $filter
// marches down the $data array:
data: {$filter: {
input: "$data",
as: "z",
cond: { $lt: [ {$add:["$$z.a","$$z.b"]} , "$other" ]}
}}
}}
]);
c = db.foo.aggregate([
{$project: {_id:true,
data: {$filter: {
input: "$data",
as: "z",
cond: { $or: [ {$gt:["$$z.a",3]}, {$lt:["$$z.b",7]} ] }
}}
}}
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.