【问题标题】:Update_one or insert_many to update records in mongodb?Update_one 或 insert_many 更新 mongodb 中的记录?
【发布时间】:2021-11-13 16:55:52
【问题描述】:

我是MongoDB 的新手,并且已经在我的收藏中插入了一个表格。现在我有了新数据(添加了新行并更新了值),但我不知道update_oneupdate_many 应该使用哪一个来更新集合中的记录。

我的数据库中的数据

from pymongo import MongoClient, UpdateOne
import pandas as pd

{
    "_id" : ObjectId("6143b5b78d248ba8ed0c3d88"),
    "Sector" : "A",
    "RKK_T" : 0.15,
    "RKK_M" : 0.2,
    "lastModified" : ISODate("2021-09-16T22:23:45.411Z")
},
{
    "_id" : ObjectId("6143b5b78d248ba8ed0c3d89"),
    "Sector" : "B",
    "RKK_T" : 0.22,
    "RKK_M" : 0.3,
    "lastModified" : ISODate("2021-09-16T22:23:45.411Z")
}

这是我要推送到数据库的新数据

data = [{
    "_id" : "6143b5b78d248ba8ed0c3d88",
    "Sector" : "A",
    "RKK_T" : 0.15,
    "RKK_M" : 0.25,
    "lastModified" :datetime.utcnow()
},
{
    "_id" : "6143b5b78d248ba8ed0c3d89",
    "Sector" : "B",
    "RKK_T" : 0.22,
    "RKK_M" : 0.3,
    "lastModified" : datetime.utcnow()
},
{
    "_id" : "6143b5b78d248ba8ed0c3d90",
    "Sector" : "C",
    "RKK_T" : 0.25,
    "RKK_M" : 0.32,
    'RKK_K' : 0.4,
    "lastModified" : datetime.utcnow()
}
]

    df = pd.DataFrame(data, columns=['_id', 'Sector', 'RKK_T', 'RKK_M', 'lastmodified'])
    df

    _id                     Sector  RKK_T   RKK_M   lastmodified
0   6143b5b78d248ba8ed0c3d88    A   0.15    0.25    NaN
1   6143b5b78d248ba8ed0c3d89    B   0.22    0.30    NaN
2   6143b5b78d248ba8ed0c3d90    C   0.25    0.32    NaN

所以我认为我需要按每个 Sector 过滤并更新 RKK_TRKK_M 列的值。

所以根据我的研究,我认为用新的data 更新collection 的一种方法是

  for i in range(len(data)):
   print(i)
   for key, values in data[i].items():

#        print(key, values)

        collection.update_one({'Sector': 'Sector'},
                                {'$set': {key.keys()[i]: values.values()[i]}, "$currentDate": {"lastModified": True}}, 
                                upsert=True)

但出现此错误

AttributeError: 'str' 对象没有属性 'keys'

我真的需要帮助来启动:) 提前致谢!

pymongo update_one(), upsert=True without using $ operators

PyMongo & Pandas - Update multiple records in MongoDB collection from dataframe by matching id

How do I update a Mongo document after inserting it?

【问题讨论】:

    标签: python mongodb nosql pymongo


    【解决方案1】:

    使用批量写入

    像这样创建

    a = []
    b = {}
    for d in data :
        b = {'updateOne':{
              "filter": {'Sector':d['Sector']},
               "update":{'$set':{
                          "RKK_T":d["RKK_T"],
                           "RKK_M" : d["RKK_M"],
                           'RKK_K' :d["RKK_K"],
                           "lastModified" :d["lastModified"]
                         }}
             }}
        a.append(b)
        db.collection.bulk_write(a)
    

    会是这样的

    db.collection.bulk_Write( [
       { updateOne :
          {
             "filter": {Sector:"A"},
             "update":{$set:{"RKK_T" : 0.25,
                             "RKK_M" : 0.32,
                              'RKK_K' : 0.4,
                              "lastModified" : datetime.utcnow()}}           
                          
          },
       { updateOne :
          {
             "filter": {Sector:"B"},
             "update":{$set:{"RKK_T" : 0.25,
                             "RKK_M" : 0.32,
                              'RKK_K' : 0.4,
                              "lastModified" : datetime.utcnow()}}           
                          
          },
       { updateOne :
          {
             "filter": {Sector:"A"},
             "update":{$set:{"RKK_T" : 0.25,
                             "RKK_M" : 0.32,
                              'RKK_K' : 0.4,
                              "lastModified" : datetime.utcnow()}}           
                          
          }
    ]
    )
    

    【讨论】:

    • 我收到了这个错误'dict' object has no attribute '_add_to_bulk'
    猜你喜欢
    • 2015-08-16
    • 1970-01-01
    • 2020-07-04
    • 2014-11-16
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多