首页 > 解决方案 > MongoDB中的graphlookup - 查询

问题描述

我有一个数据集

db.users.insertMany([ {"_id":1, "name":"abcd" }, {"_id":2, "name":"abcd"}, {"_id":3, "name": "abcd" }, {"_id":4, "name":"abcd"}, {"_id":5, "name":"abcd" }, {"_id":6, "name":"abcd "}, {"_id":7, "name":"abcd" }, {"_id":8, "name":"abcd"}, {"_id":9, "name":"abcd"} ,{“_id”:10,“名称”:“abcd”},{“_id”:11,“名称”:“abcd”},{“_id”:12,“名称”:“abcd”},{ "_id":13, "name":"abcd"}, {"_id":14, "name":"abcd"}, {"_id":15, "name":"abcd"}, {"_id":16, "name":"abcd"}, ])

db.users_hirarchy.insertMany([{ “_id”: “1101”, “_from”: 14, “_to”: 15 },{ “_id”: “1102”, “_from”: 14, “_to”: 16 } ,{“_id”:“1103”,“_from”:15,“_to”:3 },{“_id”:“1104”,“_from”:15,“_to”:5 },{“_id”: “1105”,“_from”:15,“_to”:7 },{“_id”:“1106”,“_from”:3,“_to”:1 },{“_id”:“1107”,“_from “:3,“_to”:2 },{“_id”:“1108”,“_from”:3,“_to”:4 },{“_id”:“1109”,“_from”:3,“_to ": 4 },{ "_id": "1110", "_from": 3, "_to": 4 },{ "_id":“1111”,“_from”:3,“_to”:4 }

])

我想要实现的是这样的

{
 nodes:[
 {
 "_id" : 3,
 "name": "abcd"
 },
 
 {
 "_id" : 4,
 "name": "abcd"
 }
 ] ,
 hirarchies : [
 {
 "_id" : 3,
 "Hierachy" : [
 {
 "_id" : "1106",
 "_from" : 3.0,
 "_to" : 1.0,
 "depth" : NumberLong(0)
 },
 {
 "_id" : "1107",
 "_from" : 3.0,
 "_to" : 2.0,
 "depth" : NumberLong(0)
 } ] },
 {
 "_id" : 4,
 "Hierachy" : [
 {
 "_id" : "1106",
 "_from" : 3.0,
 "_to" : 1.0,
 "depth" : NumberLong(0)
 } ] } ]

我写了一个查询,但它没有给出所需的结果。如何使用 graphlookup 来做到这一点。我尝试过的查询是

 db.users.aggregate([
 { $graphLookup: {
 from: "users_hirarchy",
 connectToField: "_from",
 startWith: "$_id",
 maxDepth: 0,
 connectFromField: "_to",
 depthField: "depth",
 as: "hirarchy"
 } } ,
 {$project:{"Data":{
 "id":"$_id",
 "name":"$name"},
  
"Hierachy":"$hirarchy"}
 }])

我怎样才能达到我想要的输出?

标签: jsonmongodbformattinglookupgraphlookup

解决方案


所以我使用 facet 来实现这一点

db.users.aggregate([
{ $graphLookup: {
from: "users_hirarchy",
connectToField: "_from",
startWith: "$_id",
maxDepth: 0,
connectFromField: "_to",
depthField: "depth",
as: "hirarchy"
}
},  {
    $facet: {
        "Node": [
        {
          $project: {
            "hirarchy": 0
          }
        }],
      "hirarchy": [
        {
          $project: {
            "hirarchy": 1,
            "_id": 1
          }
        }

]}}
])

推荐阅读