如何为其他字段的每个值获取字段的不同值?

时间:2019-01-03 19:57:11

标签: node.js mongodb mongoose

假设我的库存数据如下:

[
  {"_id":"0001","name":"test_001","value":"abc"},
  {"_id":"0002","name":"test_001","value":"abc"},
  {"_id":"0003","name":"test_001","value":"xyz"},
  {"_id":"0004","name":"test_003","value":"abc"}
]

现在我希望结果是这样的:

{
  "gouped": {
    "test_001": ["abc", "xyz"],
    "test_002": ["abc"]
  }
}

我使用$lookup

尝试了类似的操作
db.inventory.aggregate([
  {
    $lookup:
      {
        from: "inventory",
        let: { name: "$name", value: "$value" },
        pipeline: [
          { $match:
              { $expr:

                { $eq: [ "$name",  "$$name" ] }

              }
          },
          { $project: { grouped: 1, name: 1, value: 1 } }
        ],
        as: "grouped"

      }
  },
  { $project : {   grouped : 1 } }
])

这给了我这样的结果:

{ "_id" : "001", "grouped" : [ 
{ "_id" : "001", "name" : "test_001", "value" : "abc" }, 
{ "_id" : "002", "name" : "test_001", "value" : "abc" }, 
{ "_id" : "003", "name" : "test_001", "value" : "xyz" }] }

我想,即使我采用上述格式并使用唯一的value也可以。然后,我可以使用javascript取得最终结果。

0 个答案:

没有答案