【发布时间】:2020-12-09 23:17:56
【问题描述】:
我有这些收藏:
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, item: "a", 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
}
);
我也在使用 Mongoose,但使用填充失败。 有什么方法可以得到我的结果?
在这里,我更新了我的聚合管道,
[
{
$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", preserveNullAndEmptyArrays: false} },
]
}
},
{ $unwind: { path: "$owner", preserveNullAndEmptyArrays: true} },
{ '$sort': { item: 1 } },
{ '$skip': 0 },
{ '$limit': 20 } ]
【问题讨论】:
-
您有 3 个集合,只有 1 个查找列表->用户。您至少需要另一个查找来将 subs 添加到方程中
标签: mongodb mongoose aggregation-framework aggregate mongoose-populate