mongodb 嵌套对象查找

问题描述 投票:0回答:1

我想达到爱好模式中的每个子爱好,但我不知道如何正确地做到这一点。谁能帮我解决这个问题吗?

{
  $lookup: {
    from: "hobbies",
    let: {
      vid: "$surveyTargetHobbies",
    },
    pipeline: [
      {
        $match: {
          $expr: {
            $in: [
              "$_id",
              {
                $map: {
                  input: "$$vid",
                  in: {
                    $toObjectId: "$$this",
                  },
                },
              },
            ],
          },
        },
      },
    ],
    as: "surveyTargetHobbies",
  },
},

我有 subHobbies id 数组作为 SurveyTargetHobbies。我想通过此查找查看 subHobbies 标题,但我无法在爱好模式中获取 subHobbies 对象。

mongodb mongoose mongodb-query aggregation-framework
1个回答
0
投票

我想你想要这样的东西:

db.coll.aggregate([
  {$lookup: {
      from: "hobbies",
      let: {
        vid: {$map: {
            input: "$surveyTargetHobbies",
            in: {$toObjectId: "$$this"}
        }}
      },
      pipeline: [
        {$match: {$expr: {$in: ["$_id", "$$vid"]}}},
        {$project: {_id: 0, title: 1}}
      ],
      as: "surveyTargetHobbies"
  }}
])

查看它在 mongoDB Playground 上的工作原理

© www.soinside.com 2019 - 2024. All rights reserved.