【问题标题】:Mongodb - populate with limit on items and get total count of those itemsMongodb - 填充项目限制并获取这些项目的总数
【发布时间】:2020-03-23 05:34:20
【问题描述】:

我的查询如下所示:

const articles = await Article.find(query)
    .populate({
      path: 'votedUsers', // array of users id
      select: 'title name username',
      options: {
        limit: 3, 
        sort: { createdAt: -1 },
      },
    })
    .exec()

结果:

[
 {
   title: 'Article title',
   votedUsers: [,,], // array of populated users with limit of 3
   totalCountVoted: 200 // need to add this field 
 }
]

我想查找文章并填充 votedUsers 属性,但限制为 3 个用户,但同时 我需要知道votedUsers 属性中有多少个 id。

例如,可能有 200 个用户对那篇文章进行了投票,但我只需要知道这个数字并只填充其中的 3 个。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以使用matchlookupproject 阶段以及slicesize 运算符尝试以下聚合:

    (请注意,lookup from 中的“users”值必须是物理集合名称。)

    app.get("/article", async (req, res) => {
      const data = await Article.aggregate([
        {
          $match: {
            category: "Category1"
          }
        },
        {
          $lookup: {
            from: "users",
            localField: "votedUsers",
            foreignField: "_id",
            as: "users"
          }
        },
        {
          $project: {
            title: 1,
            votedUsers: { $slice: ["$users", 3] },
            totalCountVoted: { $size: "$users" }
          }
        }
      ]);
    
      res.send(data);
    });
    

    这会给你这样的结果:

    [
        {
            "_id": "5dded78f8f30c402b0fac309",
            "title": "Article1",
            "votedUsers": [
                {
                    "_id": "5dded60a84523642bc27f511",
                    "__v": 0,
                    "name": "User1"
                },
                {
                    "_id": "5dded61384523642bc27f512",
                    "__v": 0,
                    "name": "User2"
                },
                {
                    "_id": "5dded61b84523642bc27f513",
                    "__v": 0,
                    "name": "User3"
                }
            ],
            "totalCountVoted": 8
        },
        {
            "_id": "5dded7c18f30c402b0fac30a",
            "title": "Article2",
            "votedUsers": [
                {
                    "_id": "5dded61b84523642bc27f513",
                    "__v": 0,
                    "name": "User3"
                },
                {
                    "_id": "5dded63c84523642bc27f514",
                    "__v": 0,
                    "name": "User4"
                },
                {
                    "_id": "5dded64484523642bc27f515",
                    "__v": 0,
                    "name": "User5"
                }
            ],
            "totalCountVoted": 8
        }
    ]
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-11
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 2012-11-26
      • 2020-07-07
      相关资源
      最近更新 更多