首页 > 解决方案 > 如何在 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 返回值的方法吗?

提前致谢。

标签: mongodb

解决方案


你必须拆分你的操作。先获取集合,然后运行一个函数来返回你想要的值:

  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 集合的奇怪方式。如果您无法使用常规查找方法访问数据,我肯定会建议您重组您的收藏。


推荐阅读