从阵列内容动态添加密钥

时间:2017-08-02 11:44:33

标签: javascript mongodb aggregation-framework

如何在MongoDB中动态添加字段?我有一个数组,我想用它来创建列。例如,从中,

if let jsonOject = responseObject as? NSArray {
    // mean your responce is array type
}
else{
    // oterwise your responce in not array
}

我想这样做,

/* 1 */
{
    "date" : "2017-07-30",
    "brand" : [ 
        {
            "name" : "Apple",
            "quantity" : 31
        }
    ],
    "total" : 31
}

/* 2 */
{
    "date" : "2017-08-02",
    "brand" : [ 
        {
            "name" : "Apple",
            "quantity" : 1
        }, 
        {
            "name" : "Samsung",
            "quantity" : 6
        }
    ],
    "total" : 7
}

/* 1 */ { "date" : "2017-07-30", "Apple": 31, "Samsung": 0, "total" : 31 } /* 2 */ { "date" : "2017-08-02", "Apple": 1, "Samsung": 6, "total" : 7 } 运算符可以添加字段,但如何将其用于多个字段?

1 个答案:

答案 0 :(得分:0)

你可以做到,但说实话,这是一种浪费。在您拥有的地方使用$replaceRoot$arrayToObject

db.collection.aggregate([
  { "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": {
        "$concatArrays": [
          [{ "k": "date", "v": "$date" }],
          { "$map": {
            "input": "$brand",
            "as": "b",
            "in": { "k": "$$b.name", "v": "$$b.quantity" }
          }},
          [{ "k": "total", "v": "$total" }]
        ]
      }
    }
  }}
])

简单地从光标转换实际上要好得多。就像在shell中一样:

db.collection.find().map( doc =>
  Object.assign(
    { date: doc.date },
    doc.brand.map(d => ({ [d.name]: d.quantity }) )
      .reduce((acc,curr) => Object.assign(acc,curr),{}),
    { total: doc.total }
  )
)

同样的事情:

[
    {
        "date" : "2017-07-30",
        "Apple" : 31.0,
        "total" : 31.0
    },
    {
        "date" : "2017-08-02",
        "Apple" : 1.0,
        "Samsung" : 6.0,
        "total" : 7.0
    }
]