首页 > 解决方案 > 如何使用 Mongodb 获取(随机文档并使用 $slice 限制数组元素)

问题描述

我想获得一个随机的帖子文档以及每个帖子的至少 2 或 3 条第一条评论。对于第一步,我使用下面的代码来获取随机文档,它运行良好,但是对于第二步(获取每个帖子的前 3 条评论我有问题。有什么建议吗?

db.posts.aggregate([{$sample: {size: 5}}])

这是我的帖子集:

{
    "_id" : ObjectId("60e11f4bb73a901dfcb70712"),
    "username" : "user_001",
    "description" : "hello my friend",
    "comments" : [ 
        {
            "_id" : ObjectId("60e11ff0ae963901d89e13ee"),
            "username" : "user_1",
            "comment" : "this is first comment of this post"
        }, 
        {
            "_id" : ObjectId("60e1220257f2e027542a7d06"),
            "username" : "user_2",
            "comment" : "this is second comment of this post"
        }, 
        {
            "_id" : ObjectId("60e1256021f48f0ce43e39b3"),
            "username" : "user_3",
            "comment" : "this is a test comment"
        }, 
        {
            "_id" : ObjectId("60e1259321f48f0ce43e39b7"),
            "username" : "user_4",
            "comment" : "test 4"
        }
    ]
}


{
    "_id" : ObjectId("60e1290fe14b3a1584275210"),
    "username" : "user_002",
    "description" : "love is love",
    "comments" : [ 
        {
            "_id" : ObjectId("60e11ff0ae963901d89e13ea"),
            "username" : "user_5",
            "comment" : "this is first comment of this post"
        }, 
        {
            "_id" : ObjectId("60e1220257f2e027542a7d0f"),
            "username" : "user_1",
            "comment" : "this is second comment of this post"
        }
    ]
}


{
    "_id" : ObjectId("60e1290fe14b3a1584275212"),
    "username" : "user_003",
    "description" : "test post",
    "comments" : [ 
        {
            "_id" : ObjectId("60e11ff0ae963901d89e13aa"),
            "username" : "user_5",
            "comment" : "test comment"
        }, 
        {
            "_id" : ObjectId("60e1220257f2e027542a7d0c"),
            "username" : "user_8",
            "comment" : "ha ha ha"
        },
        {
            "_id" : ObjectId("60e1220257f2e027542a7d46"),
            "username" : "user_10",
            "comment" : "comment..."
        }
    ]
}```

标签: mongodbaggregate

解决方案


您可以通过添加切片查询获得前 3 条评论,如下所示。

db.posts.aggregate([
    {
        $sample: {size: 5}
    }, 
    {
        $project: {
            comments: {$slice: ["$comments", 3]}
        }
    } 
])

请检查此链接以获取更多详细信息。


推荐阅读