在聚合mongodb中填充字段

时间:2018-12-11 07:51:09

标签: mongodb mongoose mongodb-query aggregation-framework

我正在使用以下聚合查询从两个集合中获取数据:

let condition = {assignId:mongoose.Types.ObjectId(req.params.id)};
Project.aggregate([
    {
      $match: condition  
    },
    {
      "$group":{
        "_id": "$_id"
      }
    },
    { 
      "$lookup": {
        "from": "worksheets",
        "let": { "projectId": "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$projectId", "$$projectId" ] }}},
          { "$group": {_id:"$projectId", totalHours:{"$sum": "$hours"}}}
        ],
        "as": "project"
      }
    }
])
.then((data)=>{
    res.json(data);
})

并获得以下结果:

[
 {
    "_id": "5c0a4083753a321c6c4ee024",
    "project": [
        {
            "_id": "5c0a4083753a321c6c4ee024",
            "totalHours": 10
        }
    ]
 },
 {
    "_id": "5c0a2a8897e71a0d28b910ac",
    "project": [
        {
            "_id": "5c0a2a8897e71a0d28b910ac",
            "totalHours": 6
        }
    ]
 }
]

我想填充项目Array内的_id字段。为此,我需要做哪些更改?

1 个答案:

答案 0 :(得分:0)

您可以使用以下汇总

Project.aggregate([
  { "$match": condition },
  { "$group":{ "_id": "$_id" }},
  { "$lookup": {
    "from": "worksheets",
    "let": { "projectId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$projectId", "$$projectId" ] }}},
      { "$group": {_id:"$projectId", totalHours:{"$sum": "$hours"}}},
      { "$lookup": {
        "from": "projects",
        "let": { "projectId": "$_id" },
        "pipeline": [
          { "$match": { "$expr": { "$eq": [ "$_id", "$$projectId" ] }}},
          { "$project": { "projectName": 1 }}
        ],
        "as": "project"
      }}
    ],
    "as": "worksheet"
  }}
])