7

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:)

1
  • for(i in y.name){ print(y.name[i]) } Commented Oct 20, 2013 at 11:14

1 Answer 1

18

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);
            });
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.