![](/img/trans.png)
[英]How to filter a collection based on each array item in a doc field in Mongodb
[英]MONGODB - adding a field in collection to a field in Item array
假设我有以下原型的文档。
{
cust_id: "abc123",
ord_date: ISODate("2012-11-02T17:04:11.102Z"),
status: 'A',
price: 50,
items: [
{ sku: "xxx", qty: 25, price: 1 },
{ sku: "yyy", qty: 25, price: 1 }
]
}
我的要求是获取SKU“ XXX”的总价格为50 * 25(价格乘以数量)。 如何在MONGODB中获得此查询的结果?
db.YOUR_COLLECTION.aggregate({
$match: {
items.sku: "xxx"
},
$project: {
"product": {$multiply: ["$items.qty","$items.price"]},
_id: 0
}
});
我可以通过将查询分为以下两个块来实现此目的的解决方案。
var pipe1 = [
{
{
“ $ unwind”:“ $ items”
},
$match: {
items.sku: "xxx"
},
$project: {
"product":
{
$ multiply:[“ $ items.qty”,“ $ items.price”]
},_id:0}}];
R = db.tb.aggregate(pipeline);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.