json - 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"}
}])
我怎样才能达到我想要的输出?
解决方案
所以我使用 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
}
}
]}}
])
推荐阅读
- here-api - 集群标记上的过滤器 [HERE maps JS API]
- python - Python中的Excel值替换
- dataset - 如何在 GCP Data Fusion 中摄取 Table 类型的数据集以用作 Wrangler 插件中指令“table-lookup”中的查找表
- opencv - ModuleNotFoundError:谷歌珊瑚孟德尔 4.0 中没有名为“cv2”的模块
- oracle - SSRS 2017 未连接到 ORACLE 数据库
- tfs - tf14092 此项目的父项有一个挂起的删除,必须先签入
- reactjs - 在另一个类中反应的本地存储处理
- php - mysql 按多个表分组
- c# - 我如何在 Asset Bundles 包中更改或添加特定资产,而不发送我不想更改的所有旧资产(统一)
- amazon-web-services - 如何使用 Chef Cookbook 配置 AWS 资源?