Python MongoDB如何使用Update_many查询?

2021年3月30日09:51:39 发表评论 1,865 次浏览

本文概述

MongoDB是NoSQL数据库管理系统。与MySQL不同, MongoDB中的数据不存储为关系或表。 mongoDB中的数据存储为文档。文档是类似于Javascript/JSON的对象。 MongoDB中更正式的文档使用BSON。PyMongo是用于Python的MongoDB API。它允许使用python脚本从MongoDB数据库读取和写入数据。它需要在系统上同时安装python和mongoDB。

Update_many()

在更高版本的MongoDB(3.xx及更高版本)中不建议使用更新功能。可以使用" multi = true"将早期更新功能用于单个更新和多个更新。但是在较新版本的mongoDB中, 建议使用update_many()和update_one()。

主要区别在于, 如果查询要更新单个或多个文档, 则用户需要提前计划。

语法如下:

db.collection.updateMany(
   <filter>, <update>, {
     upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint:  <document|string>
   }
)

更新MongoDB中的运算符

设定值:

  • $set:用于设置字段值。
  • $setOnInsert:仅在插入新文档时更新值。
  • $unset:删除该字段及其值。

数值运算符:

  • $inc:将值增加给定值。
  • $min/$max:返回最小值或最大值。
  • $mul:将值乘以给定的数量。

杂项运算符:

  • $currentDate:将字段的值更新为当前日期。
  • $rename:重命名字段

样本数据库:

Python MongoDB – Update_many查询1

我们将在本文中看到一些用例, 其中更新许多记录可能很有用:

  1. 根据条件更改或递增几个元素。
  2. 在多个或所有文档中插入一个新字段。

范例1:所有分数大于35的学生都通过了考试。

Python3

from pymongo import MongoClient
  
  
# Creating an instance of MongoClient 
# on default localhost
client = MongoClient( 'mongodb://localhost:27017' )
  
# Accessing desired database and collection
db = client.gfg
collection = db[ "classroom" ]
  
# Update passed field to be true for all
# students with marks greater than 35
collection.update_many(
     { "marks" : { "$gt" : "35" } }, {
             "$set" : { "passed" : "True" }
         }
)

查询后的数据库:

Python MongoDB – Update_many查询2

范例2:新的称为地址的字段已添加到所有文档

python

from pymongo import MongoClient
  
  
# Creating an instance of MongoClient 
# on default localhost
client = MongoClient( 'mongodb://localhost:27017' )
  
# Accessing desired database and collection
db = client.gfg
collection = db[ "classroom" ]
  
# Address filed to be added to all documents
collection.update_many(
         {}, { "$set" :
             {
                 "Address" : "value"
             }
         }, # don't insert if no document found
    upsert = False , array_filters = None
    )

数据库查询后:

Python MongoDB – Update_many查询3

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: