我面临着一个与从MongoDB集合中获取数据有关的问题。
我在MongoDB数据库中有以下集合。
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
])
我有一个下面的查询:
db.inventory.find( { dim_cm: { $gt: 25 } } )
Result: { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }
然而,我希望结果应该是。
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 30 ] }
是否可以得到上述结果。我已经尝试了不同的方法,但不幸的是我无法找到任何解决方案。
我们可以使用 $filter
在 aggregate
管道来过滤数组
类似
db.collection.aggregate([
{
$match: { // to filter the documents
dim_cm: { $gt: 25 }
}
},
{
$project: {
_id: 1,
item: 1,
qty: 1,
tags: 1,
dim_cm: {
$filter: { // to filter the array
input: "$dim_cm",
as: "item",
cond: {
$gt: ["$$item", 25]
}
}
}
}
}
])
你可以在这里测试 艋舺游乐场
希望对你有帮助