mongodb-将对象数组(键:“键名”,值:“值”)转换为具有相应值的名为“键名”的字段

时间:2019-06-13 08:49:15

标签: arrays mongodb aggregation-framework data-science data-analysis

我的mongodb文档的当前结构是:

{
  "_id": "5c9376110a32bd172c0c5a28",
  "timestamp": 1553168075444,
  "content": [
    {
      "name": "temperature_x",
      "value": 2
    },
    {
      "name": "temperature_y",
      "value": 2
    },
    {
      "name": "temperature_z",
      "value": 0
    }
  ]
},
{
  "_id": "5c9376110a32bd172c0c5a28",
  "timestamp": 1553168075444,
  "content": [
    {
      "name": "temperature_x",
      "value": 2
    },
    {
      "name": "vibration_x",
      "value": 21
    },
    {
      "name": "vibration_z",
      "value": 10
    }
  ]
}

我想获得一个可查询的快捷方式(视图?),我将使用python查询以进行数据分析/数据科学,其中所需的文档结构为:< / p>

{
  "_id": "5c9376110a32bd172c0c5a28",
  "timestamp": 1553168075444,
  "temperature_x": 1,
  "temperature_y": 2,
  "temperature_z": 0
},
{
  "_id": "5c9376110a32bd172c0c5a28",
  "timestamp": 1553168075444,
  "temperature_x": 2,
  "vibration_y": 21,
  "vibration_z": 10
}

欢迎任何帮助

谢谢

A

2 个答案:

答案 0 :(得分:0)

dictt={
  "_id": "5c9376110a32bd172c0c5a28",
  "timestamp": 1553168075444,
  "content": [
    {
      "name": "temperature_x",
      "value": 1
    },
    {
      "name": "temperature_y",
      "value": 2
    },
    {
      "name": "temperature_z",
      "value": 0
    }
  ]
}

new_dict=dictt.copy()

for i in dictt['content']:
    new_dict[i['name']]=i['value']

new_dict["content"]=None
print(new_dict)

或者您可以就地进行

dictt={
  "_id": "5c9376110a32bd172c0c5a28",
  "timestamp": 1553168075444,
  "content": [
    {
      "name": "temperature_x",
      "value": 1
    },
    {
      "name": "temperature_y",
      "value": 2
    },
    {
      "name": "temperature_z",
      "value": 0
    }
  ]
}



for i in dictt['content']:
    dictt[i['name']]=i['value']

dictt["content"]=None
print(dictt)

答案 1 :(得分:0)

您可以使用以下汇总

Unable to locate credentials. You can configure credentials by running "aws configure".

Output

db.collection.aggregate([
  { "$replaceRoot": {
    "newRoot": {
      "$mergeObjects": [
        "$$ROOT",
        { "$arrayToObject": {
          "$map": {
            "input": "$content",
            "in": {
              "k": "$$this.name",
              "v": "$$this.value"
            }
          }
        }}
      ]
    }
  }},
  { "$project": { "content": 0 }}
])