在同一 collection 中查找值(嵌套查找)

Find value in the same collection (nested finds)

我有collection只动物,像这样

const animal1 = {
    id: '001',
    name: "cat",
    num: '001',
    strength: 2,
    family: "felines",
    animalsRelated:[ 
        {
            "num" : "002",
            "name" : "Tiger"
        }, 
        {
            "num" : "003",
            "name" : "Lion"
        }
    ]
}

const animal2 = {
    id: "002",
    num: "002",
    name: "Tiger",
    strength: 4,
    family: "felines"
}

const animal3 = {
    id: "003",
    num: "003",
    name: "Lion",
    strength: 2,
    family: "felines"
}

如果他们的任何相关动物的强度超过 3,我只需要尝试查找猫的查询。在这种情况下,查询将为我们提供猫,但如果动物 2 的强度为 2,则不会为我们提供猫,它不会给我们任何东西。 任何的想法?我试过匹配和查找但没有成功。谢谢你的时间。

解决方法如下

db.animals.aggregate([ 
  { $lookup: { 
      from: "animals", 
      localField: "animalsRelated.num", 
      foreignField: "num", 
      as: "animalsRelated" 
    } 
  }, 
  { $match: { "animalsRelated.strength": { $gt: 3 } } }
])

想法是使用 $lookup 执行连接,因此 "expand" 子文档变成完整的形状,然后使用 $match 强制执行约束。