mongodb - 如何在 MongoDB 文档中查找索引数组
问题描述
我有一个具有这种文档格式的集合:
{
"_id" : ObjectId("5c51fe3a6abdf0e5cd78f658"),
"0" : {
"id" : 1,
"name" : "carlos"
},
"1" : {
"id" : 2,
"name" : "foo"
},
"2" : {
"id" : 3,
"name" : "Jhon Doe"
},
"3" : {
"id" : 4,
"name" : "Max"
}
}
访问属性的唯一方法是执行一个 foreach 循环和另一个 for in 循环。
db.getCollection('tutorial').find({}).forEach( (users) => {
for(user in users){
print("ID-> " + users[user].id, " Name->" + users[user].name);
}
});
但我只能打印结果,还有另一种使用 find 返回值的方法吗?
提前致谢。
解决方案
你必须拆分你的操作。先获取集合,然后运行一个函数来返回你想要的值:
let collection = db.getCollection('tutorial').find({});
let name = () => {collection.forEach( (users) => {
for(user in users){
if(users[user].name == "foo"){
return ("ID-> " + users[user].id, " Name->" + users[user].name);
}
}
})};
或者只是创建一个变量并在运行循环时设置它
let name;
db.getCollection('tutorial').find({}).forEach( (users) => {
for(user in users){
name = ("ID-> " + users[user].id, " Name->" + users[user].name);
}
});
或类似的东西
尽管所有这些场景似乎都是处理 mongo 集合的奇怪方式。如果您无法使用常规查找方法访问数据,我肯定会建议您重组您的收藏。
推荐阅读
- regex - 修改文件中的模式匹配行以及下一行
- python - Django模板渲染没有给出预期的结果
- python - Django 测试,验证是否自动创建了 Profile
- javascript - 围绕javascript alert() 函数的算术运算
- javascript - 如何将大文件直接下载到磁盘,而不将其存储在服务器和浏览器的 RAM 中?
- c# - 捕获自定义 JsonConverter 抛出的异常
- javascript - 我无法在 Tampermonkey 的特定事件中播放声音
- python - 在 Python 中使用 Squeezenet 的 ImportError
- python - 如何在 Pandas 中使用 groupby 划分 2 个聚合列?
- javascript - 在反应中更新渲染组件的状态