mongo嵌套加入mongodb

时间:2017-03-21 17:59:17

标签: mongodb merge nested aggregation-framework

我正在尝试与MongoDb合并为2个集合。 集合是嵌套的。 我有2个收藏:

1 /选项

{
    "_id": {
        "$oid": "58c9866ff36d286bfca335b4"
    },
    "design": {
        "mainPage": {
            "imgRight": "58cc750ddc238d05dd6ca525",
            "imgLeft": "58cc750ddc238d05dd6ca526"
        }
    }
}

2 /表格

{
    "_id": {
        "$oid": "58cc750ddc238d05dd6ca525"
    },
    "imagePath": "logo.png"
}

如何进行聚合以获得此结果:

{
    "_id": {
        "$oid": "58c9866ff36d286bfca335b4"
    },
    "design": {
        "mainPage": {
            "imgRight": "58d07571d9d39e50166b5b3d",
            "form_docs" : {
                "imagePath": "logo.png"
            }
            "imgLeft": "58cc750ddc238d05dd6ca526",
            "form_docs" : {
                "imagePath": ""
            }
        }
    }
}

我正在尝试使用下面的代码段,但它不起作用:

   Options.aggregate([
        { "$unwind": "$design" },
        { "$unwind": "$design.mainPage" },

        {
          $lookup:
            {
              from: "forms",
              localField: "design.mainPage.imgLeft",
              foreignField: "_id",
              as: "form_docs"
            }
       }

])

1 个答案:

答案 0 :(得分:0)

我使用Mongoose populate()解决了我的问题。 http://mongoosejs.com/docs/populate.html

1 /定义架构:

var options = new Schema({
    design: {
      mainPage : {
        _imgLeft:[{type: Schema.Types.ObjectId, ref: 'Form'}],
        _imgRight:[{type: Schema.Types.ObjectId, ref: 'Form'}],
      }
    },
  }
);

2 /猫鼬功能是:

  Options
  .findOne()
  .populate('design.mainPage._imgLeft')
  .populate('design.mainPage._imgRight')
  .exec(function (err, obj) {
    return res.status(200).json({
      message: 'Successfull',
      obj: obj
    })
  });

感谢您的帮助