【问题标题】:Filtering By Grandchild property in mongoose按猫鼬中的孙子属性过滤
【发布时间】:2021-12-23 02:36:21
【问题描述】:

我对猫鼬很陌生,我想知道是否可以根据孙子属性进行过滤。我到处寻找,但我无法根据我正在尝试做的事情找到类似的问题。这是场景:

想象一下我有一个这样的数据库:

db={
  "parents": [
    {
      "_id": ObjectId("5a834e000102030405000000"),
      "child": ObjectId("5a934e000102030405000000")
    },
    {
      "_id": ObjectId("5a834e000102030405000001"),
      "child": ObjectId("5a934e000102030405000001")
    },
    {
      "_id": ObjectId("5a834e000102030405000002"),
      "child": ObjectId("5a934e000102030405000002")
    },
    
  ],
  "children": [
    {
      "_id": ObjectId("5a934e000102030405000000"),
      "grandchild": ObjectId("5a734e000102030405000000")
    },
    {
      "_id": ObjectId("5a934e000102030405000001"),
      "grandchild": ObjectId("5a734e000102030405000001")
    },
    {
      "_id": ObjectId("5a934e000102030405000002"),
      "grandchild": ObjectId("5a734e000102030405000002")
    }
  ],
  "grandchildren": [
    {
      "_id": ObjectId("5a734e000102030405000000"),
      "name": "grandchild1"
    },
    {
      "_id": ObjectId("5a734e000102030405000001"),
      "name": "grandchild2"
    },
    {
      "_id": ObjectId("5a734e000102030405000002"),
      "name": "grandchild3"
    }
  ]
}

我想返回所有有孙子名字为“grandchild1”的父母。

类似的东西

$match: {
      "child.grandchild.name": "grandchild1"
    }

所以结果中只会返回这个父级--

[{
  "_id": ObjectId("5a834e000102030405000000"),
  "child": ObjectId("5a934e000102030405000000")
},]

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    我在任何人反应之前就找到了答案……

    https://mongoplayground.net/p/w1kw58PzCyk

    db.parents.aggregate([
      {
        $lookup: {
          from: "children",
          localField: "child",
          foreignField: "_id",
          as: "child",
          
        }
      },
      {
        $addFields: {
          child: {
            $arrayElemAt: [
              "$child",
              0
            ]
          }
        }
      },
      {
        "$lookup": {
          from: "grandchildren",
          localField: "child.grandchild",
          foreignField: "_id",
          as: "grandchild",
          
        }
      },
      {
        $addFields: {
          grandchild: {
            $arrayElemAt: [
              "$grandchild",
              0
            ]
          }
        }
      },
      {
        $match: {
          "grandchild.name": "grandchild1"
        }
      }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 2016-12-14
      • 1970-01-01
      • 2021-01-18
      • 2023-04-02
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多