繁体   English   中英

MONGODB-将集合中的字段添加到Item数组中的字段

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM