【问题标题】:How to use $lookup instead of populate如何使用 $lookup 而不是填充
【发布时间】:2020-06-18 01:48:40
【问题描述】:

我对此很陌生,我发现我必须使用 $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 } },
    { "populate": user_id },
    { "populate": "'user_id', 'img user_name _id'" }

]).then(async function(posts) {
    //some code here
});

我想使用 $lookup 而不是这个填充函数。请帮忙

【问题讨论】:

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

这里简要介绍了如何使用基本的$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",
            ...
        }
    }
])

【讨论】:

  • 谢谢。感谢帮助
猜你喜欢
  • 2014-07-08
  • 2019-05-12
  • 2021-08-17
  • 1970-01-01
  • 2022-11-25
  • 2020-10-14
  • 2019-09-26
  • 1970-01-01
  • 2015-03-02
相关资源
最近更新 更多