如何匹配 MongoDB 中的聚合 ($graphLookup) 元素? [英] How to match aggregated ($graphLookup) elements in MongoDB?

查看:66
本文介绍了如何匹配 MongoDB 中的聚合 ($graphLookup) 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有:

{ "_id": 1, "name": "Dev", final: false }
{ "_id": 2, "name": "Eliot", "reportsTo" : "Dev", final: false }
{ "_id": 3, "name": "Ron", "reportsTo" : "Eliot", final: false }
{ "_id": 4, "name": "Andrew", "reportsTo" : "Eliot", final: false }
{ "_id": 5, "name": "Asya", "reportsTo" : "Ron", final: true }
{ "_id": 6, "name": "Dan", "reportsTo" : "Andrew", final: true }

申请后:

db.employees.aggregate([
    {$match: { final: true }},
    {$graphLookup: {
        ...
        as: "reportingHierarchy"
    }}
])

如何通过匹配层次结构对象reportingHierarchy.[].name 中显示的属性来过滤结果.例如将同时包含 AndrewEliot.

How to filter results by matching properties presented in hierarchy objects reportingHierarchy.[].name. For example will contain Andrew and Eliot at the same time.

{ "_id": 6, "name": "Dan", "reportsTo" : "Andrew", final: true,
    "reportingHierarchy": [
        { "_id": 1, "name": "Dev", final: false },
        { "_id": 2, "name": "Eliot", "reportsTo" : "Dev", final: false },
        { "_id": 4, "name": "Andrew", "reportsTo" : "Eliot", final: false }
    ]
}

推荐答案

reportingHierarchy 是这里的常规对象数组,因此您可以将下一个 $match 阶段添加到您的聚合中

reportingHierarchy is a regular array of objects here so you can add next $match stage to your aggregation

db.employees.aggregate( [
   {
      $graphLookup: {
         from: "employees",
         startWith: "$reportsTo",
         connectFromField: "reportsTo",
         connectToField: "name",
         as: "reportingHierarchy"
      }
   },
   {
      $match: {
        $and: [{ "reportingHierarchy.name": "Andrew" }, {"reportingHierarchy.name": "Eliot" }]
      }
   }
] )

这篇关于如何匹配 MongoDB 中的聚合 ($graphLookup) 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆