UPDATE_ONE或INSERT_MANY更新MongoDB中的记录? [英] Update_one or insert_many to update records in mongodb?

查看:38
本文介绍了UPDATE_ONE或INSERT_MANY更新MongoDB中的记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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’对象没有属性‘key’

我真的需要帮助才能启动:) 提前感谢!

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?

推荐答案

使用批量写入

这样创建

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()}}           
                      
      }
]
)

这篇关于UPDATE_ONE或INSERT_MANY更新MongoDB中的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆