繁体   English   中英

如何在MongoDB文档中查找索引数组

[英]How to find an index array inside the MongoDB document

我有一个使用此文档格式的收藏集:

{
    "_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循环,然后在内部执行另一个循环。

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集合的一种奇怪方法。 如果您无法使用常规find方法访问数据,我绝对建议您重组集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM