假设我的收藏集中有3个文档:
{
"_id" : ObjectId("5b759065bfd90aa9cc925349"),
"path" : "aa/bb",
"data" : {
"a" : "b"
}
}
{
"_id" : ObjectId("5b7590cabfd90aa9cc9253aa"),
"path" : "cc/dd",
"data" : {
"c" : "d",
"path_list":[{"path_ref" : "aa/bb"}]
}
}
{
"_id" : ObjectId("5b7590cabfd90aa9cc9253aa"),
"path" : "ee/ff",
"data" : {
"e" : "f",
"path_list":[{"path_ref" : "aa/cc"}]
}
}
如果存在data.path_ref,则需要将字符串替换为对象(如果字符串是有效路径)。如果没有,则什么也不做。所以我想得到:
{
"_id" : ObjectId("5b759065bfd90aa9cc925349"),
"path" : "aa/bb",
"data" : {
"a" : "b"
}
}
{
"_id" : ObjectId("5b7590cabfd90aa9cc9253aa"),
"path" : "cc/dd",
"data" : {
"c" : "d",
"path_list" : [ {"path_ref" : {
"_id" : ObjectId("5b759065bfd90aa9cc925349"),
"path" : "aa/bb",
"data" : {
"a" : "b"
}
} }]
}
}
{
"_id" : ObjectId("5b7590cabfd90aa9cc9253aa"),
"path" : "ee/ff",
"data" : {
"e" : "f",
"path_list":[{"path_ref" : "aa/cc"}]
}
}
我是mongodb的新手。我确实对聚合有所了解。请让我知道是否可能?
======== 符合stackoverflow的要求我发布了很多代码,但没有足够的描述。但是我想我已经清楚地描述了我的问题。这些只是占位符。请忽略它。
答案 0 :(得分:1)
您可以在3.6中使用以下汇总。
db.col.aggregate([
{"$unwind":{"path":"$data.path_list","preserveNullAndEmptyArrays":true}},
{"$lookup":{
"from":"col",
"localField":"data.path_list.path_ref",
"foreignField":"path",
"as":"path_ref_lookup"
}},
{"$unwind":{"path":"$path_ref_lookup","preserveNullAndEmptyArrays":true}},
{"$group":{
"_id":"$_id",
"path":{"$first":"$path"},
"data":{"$first":"$data"},
"path_refs":{
"$push":{
"$cond":[
{"$gt":["$path_ref_lookup",0]},
{"path_ref":"$path_ref_lookup"},
"$data.path_list"
]
}
}
}},
{"$addFields":{
"data.path_list":{
"$cond":[{"$eq":["$path_refs",[]]},"$$REMOVE","$path_refs"]
}
}},
{"$project":{"path_refs":0}}
])