0

I have a Company mongodb structure like this:

{ "companyName" : "SomeCompany",


"Products" : [
        {
            "productId" : "e3rQACssGkfp9zsue",
            "productCode" : "271102502",
            "memberPrice" : "200",
        },
        {
            "productId" : "e3rQACssGkfp9zsue",
            "productCode" : "271102502",
            "memberPrice" : "500",
        },
    ]
}

Each Company has a nested object called Products, which has its own attributes. How can I loop through the object to print out just the memberPrice from Products? I am trying to do something like:

console.log(Company.Products.memberPrice)

which returns undefined...

1 Answer 1

3

Use the array's forEach() method to iterate over the element's property:

var obj = { 
    "companyName" : "SomeCompany",
    "Products" : [
        {
            "productId" : "e3rQACssGkfp9zsue",
            "productCode" : "271102502",
            "memberPrice" : "200",
        },
        {
            "productId" : "e3rQACssGkfp9zsue",
            "productCode" : "271102502",
            "memberPrice" : "500",
        },
    ]
};

obj.Products.forEach(function(product){
    console.log(product.memberPrice); // 200, 500
})

-- UPDATE --

You could consider the following (thanks to @Michael) if you want to iterate the object in mongo shell, using the find() cursor's forEach() method:

db.collection.find().forEach(function(doc){
    doc.Products.forEach(function(p){ 
        print(p.memberPrice);
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

One more thing since OP tags question mongodb. why not something like db.collection.find().forEach(function(doc){doc.Products.forEach(function(p){ print(p.memberPrice)})})
@Michael That's another possible solution as well, kudos for mentioning!

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.