简体   繁体   中英

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.

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 ?

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. I would definitely recommend restructuring your collection if you can't access the data using regular find method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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