Mongodb嵌套查询

时间:2018-08-18 22:31:29

标签: node.js mongodb

我已经嵌套了对assignationMaster的查找,然后我想将此集合字段作为匹配字段引用到其他集合中,但是它没有返回期望的结果。似乎我无法正确引用AssignmentMaster字段。

下面是我用于相同代码。

module.exports.getAssignmentByClient = function(req, res) {
var query = url.parse(req.url,true).query;
var clientId = parseInt(query.clientId);

AssignmentDetail.aggregate([
    {
        $match : 
        { 
            clientId: clientId, 
        } , 
    },
    {
        $lookup:
        {
            from: "assignmentmasters",
            localField: "assignmentId",
            foreignField: "assignmentId",
            as: "assignmentMasterData"
        },            
    },
    { 
        $lookup: {
        from: "lists",
        let: { "status": "$assignmentMasterData" },
        pipeline: [
            { 
                $match: 
                    { $expr: { $and: [ 
                        { $eq: 
                            [ "$listName", "AssignmentStatus" ] 
                        },
                        { $eq: 
                            [ "$listItem", "$$status.status" ] 
                        }
                        ]
                    }
                } 
            },
        ],
        as: "assignmentStatus"
    }},


    {"$replaceRoot":{
        "newRoot":{
          "$reduce":{
            "input":[{"k":"assignmentStatus","v":"$assignmentStatus"},{"k":"assignmentMasterData","v":"$assignmentMasterData"}],
            "initialValue":"$$ROOT",
            "in":{
              "$mergeObjects":[
                {"$let":{
                  "vars":{"v":{"$arrayElemAt":["$$this.v",0]}},
                  "in":{"$arrayToObject":{
                    "$map":{
                      "input":{"$objectToArray":"$$v"},
                      "as":"val",
                      "in":{
                        "k":{"$concat":["$$this.k","-","$$val.k"]},
                        "v":"$$val.v"}
                    }
                  }}
                }},
                "$$value"
              ]
            }
          }
        }
    }},
    { 
        "$project": { 
            "assignmentStatus": 0,
            "assignmentMasterData": 0
        } 
    } 
  ],
  function (err, response) {
    if (err) throw err;
    if (!response) {
        res.status(200).json({ success: false, message: 'Somthing went wrong. Please contact admin.'});
    }
    else {
        res.status(200).json({ success: true, message: 'Successfull', data: response});
    }
  });
}

感谢您的所有帮助。

0 个答案:

没有答案