来自数组的对象内的mongodb aggregration映射值

时间:2018-12-07 10:59:15

标签: arrays node.js json mongodb mongoose

这是我要做的事情,我有用户集合和一个要约集合, 我的报价模型,

iUserID: {
    type: Schema.Types.ObjectId
},
oReport: [{
    iUserID: Schema.Types.ObjectId,
    sReason: String,
    dReportedDate: { type: Date, default: Date.now }
}]

在这里,我想在$lookup的用户模型中使用iUserID,也想在$lookup的userModel中使用oReport.iUserID

我的聚合查询就像

let query = [{
    $match: obj
},
{
    $lookup: {
        from: "users",
        localField: "iUserID",
        foreignField: "_id",
        as: "user"
    }
},
{
    $unwind: "$user"
},
{
    $lookup: {
        from: "users",
        localField: "oReport.iUserID",
        foreignField: "_id",
        as: "reportUsers"
    }
},
{
    $unwind: "$reportUsers"
},
{
    $addFields: {
        "oReport.reportUsers": "$reportUsers.sUserName",
    }
},
{
    $project: {
        user: 0,
    }
}
];

我得到的输出类似,

[
    {
      "_id": "5c0a43ca8138bd1c4d8600d3",
      "iUserID": "5c00fa32891cc20e261b9620",
      "sReason": "Obvious scam",
      "sReasonDec": "m Ipsum is simply dummying text of t make",
      "reportUsers": [
        "JOhn",
        "Don"
      ]
    },
    {
      "_id": "5c0a4ab6a8a7911d82334386",
      "iUserID": "5c0a4a03a8a7911d8233437d",
      "sReason": "Obvious scam",
      "sReasonDec": "sUserName",
      "reportUsers": [
        "John",
        "Don"
      ]
    }
  ]

预期输出应为

[
    {
      "_id": "5c0a43ca8138bd1c4d8600d3",
      "iUserID": "5c00fa32891cc20e261b9620",
      "sReason": "Obvious scam",
      "sReasonDec": "m Ipsum is simply dummying text of t make",
      "reportUsers":"JOhn"

    },
    {
      "_id": "5c0a4ab6a8a7911d82334386",
      "iUserID": "5c0a4a03a8a7911d8233437d",
      "sReason": "Obvious scam",
      "sReasonDec": "sUserName",
      "reportUsers": "Don"

    }
  ]

0 个答案:

没有答案