根据数组中嵌套字段的条件,我在mongo中加入文档时遇到问题。基本上,我想过滤外国馆藏的文件。
我正在关注Multiple Join Conditions with $lookup的官方MongoDB文档中的示例,并将其扩展为符合我的要求。
Testdata(注意,warehouse
文档由字段foo
扩展:)
db.orders.insert([
{ "_id" : 1, "item" : "almonds", "price" : 12, "ordered" : 2 },
{ "_id" : 2, "item" : "pecans", "price" : 20, "ordered" : 1 },
{ "_id" : 3, "item" : "cookies", "price" : 10, "ordered" : 60 }
])
db.warehouses.insert([
{ "_id" : 1, "stock_item" : "almonds", warehouse: "A", "instock" : 120, 'foo': [{ 'bar': 1 }] },
{ "_id" : 2, "stock_item" : "pecans", warehouse: "A", "instock" : 80, 'foo': [{ 'bar': 1 }] },
{ "_id" : 3, "stock_item" : "almonds", warehouse: "B", "instock" : 60, 'foo': [{ 'bar': 1 }] },
{ "_id" : 6, "stock_item" : "almonds", warehouse: "A", "instock" : 61, 'foo': [{ 'bar': 2 }] },
{ "_id" : 4, "stock_item" : "cookies", warehouse: "B", "instock" : 40, 'foo': [{ 'bar': 1 }] },
{ "_id" : 5, "stock_item" : "cookies", warehouse: "A", "instock" : 80, 'foo': [{ 'bar': 1 }] }
])
在查找中,我想添加附加条件foo.bar: 1
:
db.orders.aggregate([
{
$lookup: {
from: "warehouses",
let: { order_item: "$item", order_qty: "$ordered" },
pipeline: [{
$match: {
$expr: {
$and: [
{ $eq: [ "$stock_item", "$$order_item" ] },
{ $gte: [ "$instock", "$$order_qty" ] },
{ $eq: [ "$foo.bar", 1 ] }
]
}
}
}, {
$project: { stock_item: 0, _id: 0 }
}],
as: "stockdata"
}
}
])
不幸的是,这种额外条件不起作用。此外,查找不会返回单个文档。
有人能指出我正确的方向吗?我知道问题也可以通过使用展开,过滤器和组的管道来完成。
谢谢!