在mongodb放松

时间:2017-04-24 14:09:45

标签: mongodb aggregation-framework

我正在进行汇总以创建发票。所以我有3个收藏发票,pitchedProduct和产品。在我的发票中我有pitchedProduct Id所以通过使用它我能够访问PitchedProduct集合,在我的pitchedProduct集合中我有产品ID所以访问产品ID我必须首先解开pitchedProduct输出以访问其内部元素。但通过这样做,投影的发票数据也在多个对象中共享。我可以在不放松的情况下进行查询,这样就不会创建重复日期。

这是我的查询

db.invoices.aggregate([

  { $lookup : { from: "productsPitched", localField:"pid", foreignField:
    "idx", as:"pitchedProduct"  }},

  { $unwind: "$pitchedProduct" },

  { $lookup : { from: "products", localField:"pitchedProduct.pid", foreignField: "idx", as:"products"  } },

  { $project:{idx: true, pid: true, pmt: true, amtc: true, isv: true, dt:true,

   products: {idx: true, nm: true },

   pitchedProduct: { idx: true, pid: true}}}
] )

我得到的输出是

{ "_id" : ObjectId("58fde1e14afe1e3578b3ff86"), "pmt" : [ 30 ], "pid" : 

[ 87 ], "amtc" : 19550, "isv" : false, "dt" : 1493033441840, "idx" : 30, "products" : [ { "idx" : 2, "nm" : "garuda" } ] }
{ "_id" : ObjectId("58fde2704afe1e3578b3ff89"), "pmt" : [ 31, 32 ], "pid" : [ 86, 75 ], "amtc" : 143750, "isv" : false, "dt" : 1493033584309, "idx" : 31, "products" : [ { "nm" : "Garuda Lite", "idx" : 1 } ] }
{ "_id" : ObjectId("58fde2704afe1e3578b3ff89"), "pmt" : [ 31, 32 ], "pid" : [ 86, 75 ], "amtc" : 143750, "isv" : false, "dt" : 1493033584309, "idx" : 31, "products" : [ { "nm" : "Garuda Lite", "idx" : 1 } ] }

我想在不解开它的情况下访问pitchedProduct数据,因为当我展开它时,整个数据被转换成多个对象,这不是一个好的解决方案。

我怎样才能做到这一点?

如果您不理解,请随时提出任何问题。

谢谢:)

1 个答案:

答案 0 :(得分:1)

有几种方法可以解决问题,但以下解决方案更适用于您的情况。

您可以使用$addFields来提取已投放的产品pid's而不是$unwind。因此,您可以直接将pitchedproductpid传递给$lookup,就像您在pid $lookup中对db.invoices.aggregate([ { $lookup : { from: "productsPitched", localField:"pid", foreignField:"idx", as:"pitchedProduct" }}, { $addFields : {pitchedproductpid:"$pitchedProduct.pid"}}, { $lookup : { from: "products", localField:"pitchedproductpid", foreignField: "idx", as:"products" } }, { $project:{idx: true, pid: true, pmt: true, amtc: true, isv: true, dt:true,products: {idx: true, nm: true },pitchedProduct: { idx: true, pid: true}}} ] ) 所做的那样。

如下所示

plt.figure(figsize=(width, height))