mongodb - 如何使用 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..."
}
]
}```
解决方案
您可以通过添加切片查询获得前 3 条评论,如下所示。
db.posts.aggregate([
{
$sample: {size: 5}
},
{
$project: {
comments: {$slice: ["$comments", 3]}
}
}
])
请检查此链接以获取更多详细信息。
推荐阅读
- reactjs - 通过不更新状态的道具将功能从父组件传递到子组件来关闭 react-bootstrap 弹出模式
- python - 尝试使用 BeautifulSoup 打印表格的单行,但行位置不断变化
- java - 在 Eclipse 中播放视频效果很好,但是当将 java 项目导出为可运行的 JAR 文件时,它不再工作了
- c# - 如何生成具有正确命名空间前缀的 SOAP 兼容 XML 响应?
- python - 根据特定条件删除行
- android - Qt Android 应用程序错误:com.android.builder.dexing.DexArchiveMergerException
- html - 现代浏览器中的样式输入类型“文件”
- typescript - 源地图(用于浏览器扩展)在 Chrome 75、Edge 77 中对我不起作用
- groovy - 我可以允许使用 groovy-dsl 从所有来源删除吗?
- r - 将括号/括号内的数字增加指定数量的函数