mongodb - 查询 MongoDB 数组中的多个索引
问题描述
我想查询 MongoDB 文档中数组的一些特定的非连续索引。
我考虑过的选项是:
- 查询整个数组,然后在客户端脚本中按索引过滤。这是不可行的,因为对于大型数组,它将导致从数据库中获取不需要的项目(假设我只需要索引 5 和 20,但实际上数组中有 1000 个项目)。
- 每次我想从数组中选择每个索引时,多次使用 $slice。但这会导致 N 次调用。
- 我可以使用子架构代替简单的数组,其中数组中的每个项目都有一个分配的 ID,并且在查询时,我可以使用“查找”来选择那些特定的 ID。但这增加了一个我不想要的额外“id”字段。我确信必须有一种方法可以通过数组索引来选择项目。
我正在寻找一种更优雅的解决方案,我可以在一次操作中从数组中选择某些特定的索引。
测验模型中的示例文档:
{
questions: [
{
text: "Question 1",
answer: "Answer 1",
},
{
text: "Question 2",
answer: "Answer 2",
},
...
...
{
text: "Question 1000",
answer: "Answer 1000",
},
]
}
我想要以下内容:
const questions = await Quiz.find({
questions: {
$index_in: [10, 42, 66]
}
}).exec();
预期输出:
[
{
text: "Question 10",
answer: "Answer 10",
},
{
text: "Question 42",
answer: "Answer 42",
},
{
text: "Question 66",
answer: "Answer 66",
},
解决方案
如果要从数组中获取特定索引
询问
代替
- [0,2,5] 带有您想要的索引(或数组的驱动程序变量)
- 而不是
"$myarray"
,输入您的字段名称(在您的情况下"$questions"
)
$arrayElemAt
它的速度很快,因为O(1)
db.collection.aggregate([
{
"$addFields": {
"myarray": {
"$map": {
"input": [
0,
2,
5
],
"as": "i",
"in": {
"$arrayElemAt": [
"$myarray",
"$$i"
]
}
}
}
}
}
])
推荐阅读
- react-native - 通过视图反应原生导航
- python - 由于大量代码,Django 加载页面缓慢
- reactjs - 如何在reactjs中的react-multi-select-component中设置动态选择项
- javascript - 有没有办法从 Vue.js 的列表中只检查一个复选框
- html - 使用 string.replace 编辑后从 json 文件中删除反斜杠字符
- java - 如何在java中将HTTP请求头和正文作为字符串获取?
- javascript - Javascript将数组减少为所需格式
- python - 在不关闭浏览器的情况下更改 Selenium Web 驱动程序的用户代理
- python - 如何评估python中曲线的平滑度(平坦度)?
- java - 如何将新数据保存到先前活动生成的推送 ID 中?