【问题标题】:MONGODB : Retreive parent document in same collection than childs documentsMONGODB:检索与子文档相同的集合中的父文档
【发布时间】:2020-10-31 00:41:09
【问题描述】:

我对 mongoDb 的请求有点头疼。我得到了一个包含文档的集合,这些文档可以在同一个集合中有一个父文档。这是我的收藏。

父文档

{
    "_id": {"$oid": "5f9cac3598361b3370ea47c6"},
    "title": "My Title",
    "type":1,
    "question": "",
    "answerList": [],
    "__v": 0
}

孩子 1

{
    "_id": {"$oid": "5f9cac3598361b3370ea47c7"},
    "title": "My Title",
    "type":1,
    "question": "Q1 ?",
    "answerList": [
    {
         "_id": {"$oid": "5f9cac3598361b3370ea47c9"},
        "answer": "Hello1",
    }, 
    {
        "_id": {"$oid": "5f9cac3598361b3370ea47c8"},
        "answer": "Hello2",
    }],
    "parentId": {"$oid": "5f9cac3598361b3370ea47c6"},
    "__v": 0
}

孩子 2

{
    "_id": {"$oid": "5f9cac3598361b3370ea47ca"},
    "title": "My Title",
    "type":1,
    "question": "Q2",
    "answerList": [
     {
        "_id": {"$oid": "5f9cac3598361b3370ea47cc"},
        "answer": "Byebye1"
     }, 
     {
        "_id": {"$oid": "5f9cac3598361b3370ea47cb"},
        "answer": "Byebye2",
    }],
    "feedType": "SURVEY",
    "parentId": {"$oid": "5f9cac3598361b3370ea47c6"},
    "__v": 0
}

编辑

我想通过字段 questionanswerListtype 提出请求。逻辑上只返回子文档。问题是:如果某些文档有父文档,我只想要父文档,如果文档没有父文档,我想返回此文档。我不知道该怎么做,请帮助我

我的基本要求

var polls = MyModel.find({
  $and: [
    { confidentiality: ConfidentialityEnum.PUBLIC },
    {
      $or: [
        { question: { $regex: fields.query, $options: "i" } },
        {
          answerList: {
            $elemMatch: { answer: { $regex: fields.query, $options: "i" } },
          },
        },
      ],
    },
  ],
})
  .populate("createdBy", ["firstName", "lastName", "avatar"])
  .select("+voteList")
  .populate("voteList.user", ["_id", "avatar"])
  .select("+commentList")
  .populate("commentList.user", "_id")
  .then((data) => {
    return data;
  });

新请求(谢谢@Brmm)

const result = MyModel.aggregate([
  {
    $match: {
      $and: [
        { confidentiality: ConfidentialityEnum.PUBLIC },
        {
          $or: [
            { question: { $regex: fields.query, $options: 'i' } },
            {
              answerList: {
                $elemMatch: { answer: { $regex: fields.query, $options: 'i' } },
              },
            },
          ],
        }
      ]
    },
  },
  {
    $lookup: {
      from: 'questions',
      localField: 'parentId',
      foreignField: '_id',
      as: 'parent',
    },
  },
  {
    $unwind: {
      path: '$parent',
      preserveNullAndEmptyArrays: true,
    },
  },
]).then((data => {
    console.log(data);
}))

问题:

  • 在 console.log 中,我得到了有父文档而不是只有父文档的文档。

  • 是否可以使用 MyModel.aggregate 填充我的结果?

提前谢谢你! :)

亚历克斯

【问题讨论】:

    标签: mongodb mongoose typegoose


    【解决方案1】:

    您应该将数据拆分为“问题”和“答案”集合,并使用 $lookup 聚合管道。

    话虽如此,如果您真的想要这样,您可以尝试以下管道。请注意, $unwind 确保每个结果只有一个父级。如果您有多个具有相同 ID 的父母,您将获得多个单独的结果。如果你想要一个包含所有父母的数组,那么删除 $unwind。

    const result = await MyModel.aggregate([
      {
        $match: {
          $or: [
            { question: { $regex: 'Byebye', $options: 'i' } },
            {
              answerList: {
                $elemMatch: { answer: { $regex: 'Byebye', $options: 'i' } },
              },
            },
          ],
        },
      },
      {
        $lookup: {
          from: 'questions',
          localField: 'parentId',
          foreignField: '_id',
          as: 'parent',
        },
      },
      {
        $unwind: {
          path: '$parent',
          preserveNullAndEmptyArrays: true,
        },
      },
    ])
    

    【讨论】:

    • @AltoDev 如果您有其他问题,请随时提出新问题,如果我的回答对您有帮助,请接受它作为答案。
    • 你的请求只返回 Childs 元素。我编辑我的帖子以显示我测试过的代码
    猜你喜欢
    • 2013-07-12
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 2017-07-11
    相关资源
    最近更新 更多