我试图将3个集合合并为一个,但不能使其工作(与全部合并相同)。例如,我有3个收藏集:
1:活跃用户
[{_id:'', client_id:'',created:''}]
2:非活跃用户
[{_id:'', visitor_id:'',created:''}]
3:被阻止的用户
[{_id:'', blocked_id:'',created:''}]
我要做的是将所有3个集合合并为一个,按日期对它们进行排序,并确保获得前10个结果,诸如此类:
[{_id:'', client_id:'',created:''},
{_id:'', blocked_id:'',created:''},
{_id:'', visitor_id:'',created:''}]
我想到了以下代码:
collection('active).aggregate([
{
"$facet":{
"active":[
{"$match":{ "client_id": 5cfe83820c19ee3c50c8f323 }}
],
"not_active":[
{"$match":{"cust_id":"5cfe83820c19ee3c50c8f323" }}
],
"blocked":[
{"$match":{"blocked_id":"5cfe83820c19ee3c50c8f323" }}
]
}
},
{
"$skip":0
},
{
"$limit":10
},
{
"$sort":{
"created":-1
}
}
])
但是此代码返回空数组:
[ { active: [], not_active: [], blocked : []} ]
我做错了什么? 谢谢
答案 0 :(得分:0)
最后,我想出了完成这项工作的这段代码:
mongo.clients.aggregate([
{$limit:1},{$project:{_id:1}},{$project:{_id:0}},
{$lookup : {from:'active',as:'active',pipeline:[{$match:{}}]}},
{$lookup : {from:'not_active',as:'not_active',pipeline:[{$match:{}}]}},
{$lookup : {from:'blocked',as:'blocked',pipeline:[{$match:{}}]}},
{$project:{Union:{$concatArrays:['$active','$not_active','$blocked']}}},
{$unwind:"$Union"},
{$replaceRoot:{newRoot:"$Union"}},
{$skip:0},
{$limit:10},
{$sort:{'created': -1}}
]).then(x);
这里有更详细的答案: enter link description here