[英]How to find an index array inside the MongoDB document
I have one collection with this document format: 我有一个使用此文档格式的收藏集:
{
"_id" : ObjectId("5c51fe3a6abdf0e5cd78f658"),
"0" : {
"id" : 1,
"name" : "carlos"
},
"1" : {
"id" : 2,
"name" : "foo"
},
"2" : {
"id" : 3,
"name" : "Jhon Doe"
},
"3" : {
"id" : 4,
"name" : "Max"
}
}
the only way to access the properties was doing a foreach loop and another for in inside. 访问属性的唯一方法是执行foreach循环,然后在内部执行另一个循环。
db.getCollection('tutorial').find({}).forEach( (users) => {
for(user in users){
print("ID-> " + users[user].id, " Name->" + users[user].name);
}
});
But I can only print the results, there is another way to return a value using find ? 但是我只能打印结果,还有另一种使用find返回值的方法?
Thanks in advance. 提前致谢。
You have to split up your operations. 您必须拆分操作。 Get the collection first and then run a function to return the value you wish: 首先获取集合,然后运行一个函数以返回所需的值:
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);
}
}
})};
or simply create a variable and set it when you run the loops 或只是创建一个变量并在运行循环时进行设置
let name;
db.getCollection('tutorial').find({}).forEach( (users) => {
for(user in users){
name = ("ID-> " + users[user].id, " Name->" + users[user].name);
}
});
or something similar 或类似的东西
Though all of these scenarios seem like a strange way to handle a mongo collection. 尽管所有这些情况似乎都是处理mongo集合的一种奇怪方法。 I would definitely recommend restructuring your collection if you can't access the data using regular find method. 如果您无法使用常规find方法访问数据,我绝对建议您重组集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.