0

我在mydb数据库中有以下集合:

  • 购买:它包含以下格式的文件:

    {
     _id: <ObjectId>,
     name: <String>, //customer name
     purchasedItems: <Array>
              0: < Object >
                  i_name: <String> // item name
                  qntity: <Int>
              // other objects in the array
    }
    
  • sales:它包含以下格式的文档:

    {
     _id: <ObjectId>,
     i_name: <String>,
     qntity: <Int>
     cost: <Int>
    }
    

我想输出一个包含以下文档的新集合:

    {
     _id: <ObjectId>,
     name: <String>,
     cost: <Int>
    }

其中name是购买集合中客户的名称, cost是他购买的所有物品的成本。

正式地,每个项目的成本定义为:

购买.purchasedItems.qntity/sales.qntity) * sales.cost

WHERE purchase.purchasedItems.i_name=sales.i_name

输出集合中的成本是所有项目成本的总和。

我尝试了以下方法,但它不起作用:

db.purchases.aggregate([
    {$unwind: "$purchasedItems"},
    {$lookup:
        {from:"sales",
        localField:"purchasedItems.i_name",
        foreignField:"i_name",
        as: "n_cost"}
    },
    {
        $group:{
               _id: "$_id",
               name: "$name",
               cost: {$sum: {multiply:[{$divide:["$n_cost.qntity","$qntity"]},"$n_cost.cost"]}}
        }
    },
    {$out: "results"}
])

对于我做错的事情以及正确的做法,我将不胜感激。

4

1 回答 1

1

所以这里有几件事不正确。

一堆缺失的参考资料和阶段$unwind后的缺失$lookup

尝试

db.purchases.aggregate([
  {"$unwind":"$purchasedItems"},
  {"$lookup":{
    "from":"sales",
    "localField":"purchasedItems.i_name",
    "foreignField":"i_name","as":"n_cost"
  }},
  {"$unwind":"$n_cost"},
  {"$group":{
    "_id":"$_id",
    "name":{"$first":"$name"},
    "cost":{
      "$sum":{
        "$multiply":[
          {"$divide":["$purchasedItems.qntity","$n_cost.qntity"]},
          "$n_cost.cost"
        ]
      }
    }
  }},
  {"$out":"results"}
])

没有$unwind

db.purchases.aggregate([
  {"$lookup":{
    "from":"sales",
    "localField":"purchasedItems.i_name",
    "foreignField":"i_name",
    "as":"n_cost"
  }},
  {"$project":{
    "name":1,
    "cost":{
      "$sum":{
        "$map":{
          "input":{"$range":[0,{"$size":"$purchasedItems"}]},
          "as":"ix",
          "in":{
            "$let":{
              "vars":{
                "purchase":{"$arrayElemAt":["$purchasedItems","$$ix"]},
                "sales":{"$arrayElemAt":["$n_cost","$$ix"]}},
                "in":{
                  "$multiply":[
                    {"$divide":["$$purchase.qntity","$$sales.qntity"]},"$$sales.cost"
                  ]
                }
            }
          }
        }
      }
    }
  }},
  {"$out":"results"}
])
于 2018-01-27T18:23:55.053 回答