Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To loop through non associative array in mongoDB

Tags:

arrays

mongodb

I have a collection with a document having data in nested array form with array list of different format.

Input:

{ 
    "_id" : ObjectId("5262d2eaca24d995f4958083"),
    "array" : [
        {
            "name" : "sam",
            "roll" : 21 
        },  
        {
            "name" : "vam",
            "roll" : 22
        },  
        {
            "name" : "mam",
            "roll" : 23
        },  
        {
            "name" : "jam",
            "roll" : [31, 32, 33, 34]
        },
        {
            "name" : [
                {"name" : "lam" },
                {"name" : "ham" },
                {"name" : "pam" }
            ],
            "roll" :[
                {"roll" : 41},
                {"roll" : 42},
                {"roll" : 43}
            ]
        }
    ]
}

(In the above code the array[4] has different format compared to its predecessors)

I want to get all the names of array[4] i.e lam,ham,pam

Desired output:

lam
ham
pam

My Approach: I tried the following code

db.test1.find().forEach(function(x)
{
    x.array.forEach(function(y)
    {
        y.name.forEach(function(z)
        {
            print(z.name);
        })
    })
})

But this gives error reason being:

error: Sam has no method 'forEach' :

because it tries to loop through name (arraylist 1) but since it has only one data i.e 'sam', forEach doesn't work for this, cause forEach only works for associative Array's.

FYI: When I tried the same code for nested array with array format being the same for all its list, I could get the desired output.

Please help me get the code right using mongo shell.

Thanks In advance:)

like image 315
Sam Avatar asked Oct 20 '13 11:10

Sam


1 Answers

You need to check if y.name is an array and only then try to print the values. Something like this should work:

db.test1.find().forEach(function (x) {
    x.array.forEach(function (y) {
        if (y.name instanceof Array) {
            y.name.forEach(function (z) {
                print(z.name);
            });
        }
    });
});
like image 134
David Hoffman Avatar answered Sep 25 '22 01:09

David Hoffman