【问题标题】:How to populate in MongoDB without mongoose?如何在没有猫鼬的情况下填充 MongoDB?
【发布时间】:2022-11-22 03:29:10
【问题描述】:

我正在做一个大学项目,我需要用 ObjectId 填充一个对象数组,但我不能在我的项目中使用 mongoose。我有两个系列 -主题学习计划.

例子学习计划文档:

{
  _id: ObjectId('111'),
  name: "Study program 1"
  description: "Lorem ipsum dolor sit amet",
  language: "en",
  subjects: [
    {
      id: ObjectId('222'),
      optionality: "selective",
      credits: 8,
    },
    {
      id: ObjectId('333'),
      optionality: "selective",
      credits: 5
    },
  ],
}

例子主题文件:

{
  _id: ObjectId('222'),
  name: "Subject A",
  description: "Subject A description.",
},
{
  _id: ObjectId('333'),
  name: "Subject B",
  description: "Subject B description.",
}

我需要使用来自的适当文档填充 subjects 数组中的对象主题收藏基于id。基本上我正在寻找的是这个结果:

{
  _id: ObjectId('111'),
  name: "Study program 1"
  description: "Lorem ipsum dolor sit amet",
  language: "en",
  subjects: [
    {
      
      _id: ObjectId('222'),
      name: "Subject A",
      description: "Subject A description.",
      optionality: "selective",
      credits: 8,
    },
    {
      _id: ObjectId('333'),
      name: "Subject B",
      description: "Subject B description.",
      optionality: "selective",
      credits: 5
    },
  ],
}

到目前为止,我已尝试使用以下 $lookup:

{
  $lookup: {
    from: "subject",
    localField: "subjects.id",
    foreignField: "_id",
    as: "subjects",
  }
}

但这会删除 optionalitycredits 属性。有没有办法在不使用猫鼬的情况下实现这一目标?谢谢你。

【问题讨论】:

    标签: javascript mongodb mongoose lookup populate


    【解决方案1】:

    这是一种方法。

    db.studyProgram.aggregate([
      {
        "$lookup": {
          "from": "subject",
          "localField": "subjects.id",
          "foreignField": "_id",
          "as": "subjectDocs"
        }
      },
      {
        "$set": {
          "subjects": {
            "$map": {
              "input": "$subjects",
              "as": "subject",
              "in": {
                "$mergeObjects": [
                  {
                    "$first": {
                      "$filter": {
                        "input": "$subjectDocs",
                        "as": "doc",
                        "cond": {"$eq": ["$$doc._id", "$$subject.id"]}
                      }
                    }
                  },
                  {
                    "optionality": "$$subject.optionality",
                    "credits": "$$subject.credits"
                  }
                ]
              }
            }
          },
          "subjectDocs": "$$REMOVE"
        }
      }
    ])
    

    试试mongoplayground.net

    【讨论】:

      【解决方案2】:

      我也很好奇这个问题的答案。我很期待解决方案

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-25
        • 2016-07-22
        • 2020-11-19
        • 2020-09-13
        • 1970-01-01
        • 2015-07-13
        • 2016-10-10
        相关资源
        最近更新 更多