2

I use the cursor .forEach to display the data as a table.

.forEach(function(doc){
        print((doc.Id + ';' + doc.item + ';' + doc.delta);

But this does not work with data like this:

items" : [
    {
        "amount" : 1,
        "id" : 158,
}]

How do I bring them to the table using the cursor?

I need something like this:

id-itemId-amount 

57 | 158 | 1

58 | 159 | 2 

(itemID and amount from array)

1 Answer 1

1

The Mongo shell supports standard JavaScript for iterating over an array and the items attribute is an array. So, inside the 'for each function' you can iterate over the items array and print out the id and amount attributes for each subdocment in that array.

For example:

db.collection.find({}).forEach(function(doc) {
    // standard JS loop over an array
    for (var i in doc.items) {
        // print the id from the 'outer' document alongside the id  
        // and amount from each sub document in the items array
        print(doc.id + '|' + doc.items[i].id + '|' + doc.items[i].amount);
    }
})

Given the following documents ...

{ "id": 1, items" : [{"amount": 10, "id": 158}, {"amount": 11, "id": 159}]}
{ "id": 2, items" : [{"amount": 20, "id": 266}, {"amount": 21, "id": 267}]}

... the above function will print:

1|10|158
1|11|159
2|20|266
2|21|267
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.