如何使用$lookup代替populate?"/>
如何使用$lookup代替populate?
我对这个很陌生,我发现我必须使用 $lookup 而不是我的代码中的populate。由于我没有这方面的经验,我需要一些帮助,如何在下面的代码中做到这一点。
postSchemaModel.aggregate([{
"$geoNear": {
"near": { "type": "Point", "coordinates": [6.7336665, 79.8994071], "Typology": "post" },
"distanceField": "dist.calculated",
"maxDistance": 5000,
"includeLocs": "dist.location",
"spherical": true
}
},
{ "limit": limit },
{ "skip": startIndex },
{ "$sort": { "createdAt": -1 } },
{ "populate": user_id },
{ "populate": "'user_id', 'img user_name _id'" }
]).then(async function(posts) {
//some code here
});
我想用$lookup代替这个populate函数。请帮助我
回答如下:下面是一个快速草图,说明如何使用基本的 $lookup
语法。我不得不推测一些字段名,因为你没有包含所有集合的模式,但如果它们是错误的,应该是相当直接的修正。
postSchemaModel.aggregate([
{
"$geoNear": {
"near": {"type": "Point", "coordinates": [6.7336665, 79.8994071], "Typology": "post"},
"distanceField": "dist.calculated",
"maxDistance": 5000,
"includeLocs": "dist.location",
"spherical": true
}
},
{"limit": limit},
{"skip": startIndex},
{"$sort": {"createdAt": -1}},
{
$lookup: {
from: "users", //user collection name,
localField: "user", // this is the field in the post document that links to user
foreignField: "_id", // this is the field in the user document that links to localField specified above.
as: "users" // name of new field
}
},
// users is now an array of matched users (could be an empty array if no user was matched), assuming a post can only have 1 user we should unwind this
{
$unwind: {
path:"$users"
preserveNullAndEmptyArrays: true // true if you want to keep posts with no matched user.
}
},
{
//now you can $project whichever structure you want
$project: {
user_id: "$users._id",
...
}
}
])
更多推荐
如何使用$lookup代替populate?
发布评论