问题描述
我有这些收藏夹:
lists
{_id: 1,item: "a",owner: 1}
users
{_id: 1,subs: [{_id: 1,active: "Y"},{_id: 2,active: "N"}]}
subs
{_id: 1,text: "A"}
{_id: 2,text: "B"}
{_id: 1,owner: {_id: 1,subs: [{_id: {_id: 1,text: "A"},active: "Y"}]}}
我还想根据“文本”字段对其进行排序。
我尝试了汇总,但是失败了,
db.getCollection("lists").aggregate(
[
{
"$lookup" : {
"from" : "users","localField" : "owner","foreignField" : "_id","as" : "owner"
}
},{
"$match" : {
"owner.0.subs" : {
"$elemmatch" : {
"active" : "Y"
}
}
}
}
],{
"allowdiskUse" : false
}
);
我也使用猫鼬,但使用填充失败。 有什么办法可以得到我的结果吗?
在这里,我更新了聚合管道,
[
{
$lookup: {
from: "users",as: "owner",let: { owner: "$owner" },pipeline: [
{ $match: { $expr: { $eq: ["$$owner","$_id"] } } },{ $unwind: { path:"$sub",preserveNullAndEmptyArrays: false} },{ $match: { "subs.active": "Y" } },{
$lookup: {
from: "plans",localField: "subs._id",foreignField: "_id",as: "subs.plans"
}
},{ $unwind: { path:"$subs.plans",]
}
},{ $unwind: { path: "$owner",preserveNullAndEmptyArrays: true} },{ '$sort': { item: 1 } },{ '$skip': 0 },{ '$limit': 20 } ]
解决方法
您可以将查询与管道和嵌套查询一起使用,
内部查找管道为:
-
$match
您在用户集合中的所有者ID -
$unwind
解构subs
数组,因为我们需要使用subs
集合进行查找 -
$match
订阅是否处于活动状态 -
$lookup
(包含潜艇收藏) -
$unwind
解构我们从subs集合加入的subs._id
-
$group
重建subs
数组 -
$unwind
解构owner
数组 -
$sort
和item
和$skip
的分页
$limit
您的第二次编辑:在第一个$ unwind内的第一次查找中键名db.getCollection("lists").aggregate([
{
$lookup: {
from: "users",as: "owner",let: { owner: "$owner" },pipeline: [
{ $match: { $expr: { $eq: ["$$owner","$_id"] } } },{ $unwind: "$subs" },{ $match: { "subs.active": "Y" } },{
$lookup: {
from: "subs",localField: "subs._id",foreignField: "_id",as: "subs._id"
}
},{ $unwind: "$subs._id" },{
$group: {
_id: "$_id",subs: {
$push: {
_id: "$subs._id._id",text: "$subs._id.text",active: "$subs.active"
}
}
}
}
]
}
},{ $unwind: "$owner" },{ $sort: { item: 1 } },{ $skip: 0 },{ $limit: 20 }
],{ allowDiskUse: false })
错误,
sub
到
{ $unwind: { path:"$sub",preserveNullAndEmptyArrays: false} }