【问题标题】:MongoDB Nested Documents Update with python使用 python 更新 MongoDB 嵌套文档
【发布时间】:2017-03-06 23:25:37
【问题描述】:

我正在尝试聚合一些 mongoDB 记录,并从包含 1500 条记录的聚合查询中获取此返回值:

{
    "_id": {
        "Year": 2016,
        "locationID": " WL 001",
        "Day": 25,
        "Hour": 12,
        "Month": 1
    },
    "temperature": 10.858749999999999,
    "pH": 0,
    "Conductivity": 2032.375
}

如何插入temperaturepHConductivity 的结果值,以便插入数据库的数据具有以下格式?

{  
    "_id": {
        "Year": 2016,
        "locationID": " WL 001",
        "Day": 25,
        "Hour": 12,
        "Month": 1
    }, 
    "Readings": {
        "pH": { "value": 8.879 },
        "temperature": { "value": 16.81 },
        "Conductivity": { "value": 1084 }
    }
}

我尝试了几种方法,但似乎无法得到结果。

【问题讨论】:

    标签: jquery mongodb python-2.7 python-3.x pymongo


    【解决方案1】:

    您需要在聚合管道中添加一个额外的步骤来投影数据;在 pymongo 中:

    from pymongo import MongoClient
    
    uri = "mongodb://localhost:27017/"
    client = MongoClient(uri)
    db = client['test']
    
    db['test'].save({
        "_id": {
            "Year": 2016,
            "locationID": " WL 001",
            "Day": 25,
            "Hour": 12,
            "Month": 1
        },
        "temperature": 10.858749999999999,
        "pH": 0,
        "Conductivity": 2032.375
    })
    
    
    pipeline = [
    {
        "$project": {
            '_id': '$_id',
            'Readings': {
                'pH': {'value': '$pH'},
                'temperature': {'value': '$temperature'},
                'Conductivity': {'value': '$Conductivity'}
            }
        }
    },
    ]
    
    result =  db['test'].aggregate(pipeline)
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2021-11-30
      • 2015-08-27
      • 2016-11-23
      • 2010-11-11
      • 2018-04-23
      • 2021-02-13
      • 2013-03-19
      相关资源
      最近更新 更多