游标.foreach和数组数据

时间:2017-12-01 13:15:41

标签: mongodb mongodb-query

我使用光标.forEach将数据显示为表格。

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

但这不适用于这样的数据:

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

如何使用光标将它们带到表中?

我需要这样的东西:

id-itemId-amount 

57 | 158 | 1

58 | 159 | 2 

(itemID和数组中的金额)

1 个答案:

答案 0 :(得分:0)

Mongo shell支持用于迭代数组的标准JavaScript,而items属性数组。因此,在每个功能的内部'您可以遍历items数组并打印出该数组中每个子目标的idamount属性。

例如:

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);
    }
})

鉴于以下文件......

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

...以上功能将打印:

1|10|158
1|11|159
2|20|266
2|21|267
相关问题