【问题标题】:Mongoose aggregate Get sum of likes in multiple records from another collectionMongoose聚合从另一个集合中获取多条记录中的喜欢总和
【发布时间】:2021-01-06 02:23:30
【问题描述】:

我需要从用户的所有帖子中获取喜欢字段的总和
这是架构
用户架构

{ "_id": "5f5b784209393b0638f896e2", "name": "测试用户", “头像”:“https://someurl/attachments/media-6489.PNG” }

帖子架构

{ “喜欢”:[ "5f4d553370eef30017288fb0", // 其他点赞的用户 “5f4fad6cc7d4990017fb0d29”, "5f5a3c074de2d1246c99767b", "5f5b790532dd2f1de4127aa4", “5f5c6aeff8170922d44eeb7a” ], "_id": "5f65daf13ce59d0a5482ea0d", “文本”:“fdsa”, “作者”:“5f5b784209393b0638f896e2”, }

我是猫鼬的新手,在此先感谢..

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    终于让这个查询完成了所需的操作

    const postsData = await User.aggregate([
        { $match: { _id: mongoose.Types.ObjectId(req.user.id) } },
        {
            $lookup: {
                from: "posts",
                localField: "_id",
                foreignField: "author",
                as: "posts",
            }
        },
        { $unwind: "$posts", },
        {
            $group: {
                _id: "$_id",
                likes: { $sum: { $size: "$posts.likes" } }
            }
        },
    ]);
    

    【讨论】:

      猜你喜欢
      • 2021-02-11
      • 2020-05-13
      • 2018-11-23
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多