[英]MongoDB aggregation lookup pipeline query
I'm looking for help with a MongoDB lookup aggregation query.我正在寻找有关 MongoDB 查找聚合查询的帮助。
I'm trying to join two collections, namely "cafe" and "stamp".我正在尝试加入两个集合,即“cafe”和“stamp”。 During the lookup, I would like to match stamps for a given cafe and then further sort and limit the results by 10.在查找过程中,我想匹配给定咖啡馆的邮票,然后进一步排序并将结果限制为 10。
The correlated id fields are: "_id" for the cafe collection and "cafeId" in for the stamp collection.相关的 id 字段是:咖啡馆收藏的“_id”和邮票收藏的“cafeId”。
The following is what I have come up with, however there seems to be a problem when trying to match by ids between the given collections.以下是我想出的,但是在尝试按给定集合之间的 id 进行匹配时似乎存在问题。 I believe this may have something to do with Mongo not treating them as ObjectID's, but I'm unsure.我相信这可能与 Mongo 没有将它们视为 ObjectID 有关系,但我不确定。
db.cafe.aggregate([
{
$lookup: {
from: "stamp",
as: "stamps",
let: {
id: "$_id",
name: "$name"
},
pipeline: [
{ $project: { id:1, cafeId: { $toObjectId: "$$id"}, name:1 } },
{ $match: { expr: { $eq: ["$$cafeId", "$cafeId"] } } },
{ $sort: { stampDate: -1 } },
{ $limit: 10 }
]
}
}
]);
Managed to figure out how to achieve what I wanted.设法弄清楚如何实现我想要的。 Leave this here for anyone else that is trying to achieve the same results.将其留在这里,供其他试图获得相同结果的人使用。
db.cafe.aggregate([
{
$lookup: {
from: "stamp",
as: "stamps",
let: {
id: "$_id",
name: "$name" //All cafes variables,
},
pipeline: [
{
$project: {
cafeId: 1,
stampDate: 1,
stampId: 1,
cafeId: 1,
status: 1,
userId: { $toObjectId: "$userId" }
}
},
{
$match: {
$expr: {
$and: [
{
$eq: [{ $toObjectId: "$$id" }, { $toObjectId: "$cafeId" }]
},
{
$eq: [
{ $toObjectId: "$userId" },
mongoose.Types.ObjectId(req.user._id)
]
}
]
}
}
}
]
}
}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.