Python MongoDB - Mise à jour

Vous pouvez mettre à jour le contenu d'un document existant à l'aide du update() méthode ou save() méthode.

La méthode de mise à jour modifie le document existant tandis que la méthode save remplace le document existant par le nouveau.

Syntaxe

Voici la syntaxe des méthodes update () et save () de MangoDB -

>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Or,
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Exemple

Supposons que nous ayons créé une collection dans une base de données et inséré 3 enregistrements comme indiqué ci-dessous -

> use testdatabase
switched to db testdatabase
> data = [
   ... {"_id": "1001", "name": "Ram", "age": "26", "city": "Hyderabad"},
   ... {"_id": "1002", "name" : "Rahim", "age" : 27, "city" : "Bangalore" },
   ... {"_id": "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }
]
[
   {
      "_id" : "1001",
      "name" : "Ram",
      "age" : "26",
      "city" : "Hyderabad"
   },
   {
      "_id" : "1002",
      "name" : "Rahim",
      "age" : 27,
      "city" : "Bangalore"
   },
   {
      "_id" : "1003",
      "name" : "Robert",
      "age" : 28,
      "city" : "Mumbai"
   }
]
> db.createCollection("sample")
{ "ok" : 1 }
> db.sample.insert(data)

La méthode suivante met à jour la valeur de la ville du document avec l'ID 1002.

> db.sample.update({"_id":"1002"},{"$set":{"city":"Visakhapatnam"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Hyderabad" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }

De même, vous pouvez remplacer le document par de nouvelles données en l'enregistrant avec le même identifiant en utilisant la méthode save ().

> db.sample.save(
   { "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" }
)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.sample.find()
{ "_id" : "1001", "name" : "Ram", "age" : "26", "city" : "Vijayawada" }
{ "_id" : "1002", "name" : "Rahim", "age" : 27, "city" : "Visakhapatnam" }
{ "_id" : "1003", "name" : "Robert", "age" : 28, "city" : "Mumbai" }

Mettre à jour des documents à l'aide de python

Similaire à la méthode find_one () qui récupère un seul document, la méthode update_one () de pymongo met à jour un seul document.

Cette méthode accepte une requête spécifiant le document à mettre à jour et l'opération de mise à jour.

Exemple

L'exemple python suivant met à jour la valeur d'emplacement d'un document dans une collection.

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['myDB']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = [
   {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
   {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
   {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")

#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
print(doc1)
coll.update_one({"_id":"102"},{"$set":{"city":"Visakhapatnam"}})

#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")

for doc2 in coll.find():
   print(doc2)

Production

Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Documents in the collection after update operation:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}

De même, le update_many() La méthode de pymongo met à jour tous les documents qui remplissent la condition spécifiée.

Exemple

L'exemple suivant met à jour la valeur d'emplacement dans tous les documents d'une collection (condition vide) -

from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['myDB']

#Creating a collection
coll = db['example']

#Inserting document into a collection
data = [
   {"_id": "101", "name": "Ram", "age": "26", "city": "Hyderabad"},
   {"_id": "102", "name": "Rahim", "age": "27", "city": "Bangalore"},
   {"_id": "103", "name": "Robert", "age": "28", "city": "Mumbai"}
]
res = coll.insert_many(data)
print("Data inserted ......")

#Retrieving all the records using the find() method
print("Documents in the collection: ")
for doc1 in coll.find():
print(doc1)
coll.update_many({},{"$set":{"city":"Visakhapatnam"}})

#Retrieving all the records using the find() method
print("Documents in the collection after update operation: ")

for doc2 in coll.find():
   print(doc2)

Production

Data inserted ......
Documents in the collection:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Hyderabad'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Bangalore'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Mumbai'}
Documents in the collection after update operation:
{'_id': '101', 'name': 'Ram', 'age': '26', 'city': 'Visakhapatnam'}
{'_id': '102', 'name': 'Rahim', 'age': '27', 'city': 'Visakhapatnam'}
{'_id': '103', 'name': 'Robert', 'age': '28', 'city': 'Visakhapatnam'}