How To Find And Replace Or Change MongoDB Documents In Python

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

To find MongoDB documents Python and replace MongoDB documents Python, you use the replace_one() method. It’s a process that reconstructs a document, therefore, you must have the document’s entire data to pass to the method. This comes in handy when you really need a “do over” for a document. That is to say, your goal is to have none of the original document left intact after you write MongoDB documents Python replacement code.

Having said that, there might also be times when you just want to find replace MongoDB documents Python only to modify MongoDB documents Python. This tutorial explains how to do both. Learn how to find and replace or modify MongoDB documents in Python today.

Advanced users, if you want to skip the details of this tutorial and view the code to replace documents PyMongo, jump to Just the Code.

Prerequisites

  • Install MongoDB. Ensure that it’s up and running.

  • Install Python 3. Run it.

  • Download and install the Python driver PyMongo – Use the PIP3 package manager at the command line.

1
pip3 install pymongo
  • Install the BSON library so you that when you make method calls, the document’s _id and ObjectID is found by Python.
1
pip3 install bson
  • Create a MongoDB database. In a collection, you should have some documents you don’t mind losing as you find replace MongoDB documents Python and write documents PyMongo replacement method scripts. You’ll use the unimportant files to test API calls taught in this tutorial.

Import the MongoClient class

  • At the beginning of the script, import the required modules and libraries you need plus PyMongo.

  • Create an instance from the MongoClient class.

1
2
# import the MongoClient class
from pymongo import MongoClient
  • Import the ObjectID module too so that documents’ BSON ObjectID objects are recognized by Python.
1
2
# import ObjectID from MongoDB's BSON library
from bson import ObjectId
  • With the datetime library, date strings can be replaced if passed to a MongoDB document as document data. Import it just in case you want to use it.
1
2
# import the datetime library
import datetime
  • Use the time library to get timestamps with the datetime.datetime.now() method. Import it so you’ll be ready to use it when needed.
1
import time
  • Construct a MongoClient new client instance. Prepare to make API calls with the method replace_one().
1
mongo_client = MongoClient()

Use the client instance of PyMongo to get the MongoDB database and collection

  • Object instances in your database and collection you create may or may not be the MongoDB server. You can always create new names right away.

Get client object attributes of a database

Access different databases on the MongoDB server with the client object attributes.

  • As shown in the example below, the client object attribute for some_database is accessed.
1
db = mongo_client.some_database

Get the attribute of the collection for the instance of the database

  • Use the database object to make a collection object instance.
1
col = db.some_collection
  • When a collection’s name is composed of two or more separate names in the title, use a string like it’s a part of a dictionary’s key attribute.
1
2
# access a collection that has a space in its name
col = db["Some Collection"]

Verify documents are in a MongoDB collection instance

  • The method count_documents() lets you know if documents are in a collection.

  • To the method call, pass the wildcard-like ({}) dictionary object to locate all documents in a collection. The dictionary object has to be empty before you pass it.

1
2
total_docs = col.count_documents( {} )
print (col.name, "has", total_docs, "total documents.")

Make a filter dictionary object to find documents that match a certain criteria

*As the beginning parameter, dictionary objects must have a key that represents a data field name. This is a requirement for the API call methods like replace_one() in MongoDB and many others.

  • It’s a good idea to construct a filter dictionary object for later usage because you’ll likely want to use it soon.

  • The example below shows a query for a particular BSON ObjectID of a document. Import the module of the ObjectID at the script’s beginning in order to use this method.

1
query = {"_id" : ObjectId("5cfa4c0ad9edff487939dda5") }

>NOTE: Nothing will be returned if a document matching that BSON ObjectID isn’t found in the collection.

The replacement data of a MongoDB document needs a document body

  • The dictionary object is the document body. The example below shows the second parameter and that’s the document body (replacement data).
1
replacement_data = {"some text" : "ObjectRocket services"}

>NOTE: If you want to keep everything from the old document, include it in the dictionary object.

  • Pass to the replace_one() method the query and replacement_data dictionary objects. You’ll get a pymongo.results.UpdateResult returned.
1
2
# pass the `query` and `replacement_data` objects to the method call
result = col.replace_one( query, replacement_data )

>WARNING: You’ll forever lose any of the original document’s data that you don’t pass to the method replace_one().

Get a list of all of an object’s attributes with the dir() function

  • Use the dir() function, a Python built-in, to see a list of attributes and methods for the object in the form of string names.
1
results_attr = dir(result)
  • When you made the API call, Python collected important information, including data about the documents it changed.
1
[acknowledged', 'matched_count', 'modified_count', 'raw_result', 'upserted_id']
  • Some data may have been replaced if you used the replace_one() method. Confirm which ones were altered with this script.
1
2
print ("raw result:", result.raw_result)
print ("acknowledged:", result.acknowledged)
  • When you passed a filter to the method’s first parameter, it searched for document matches. Learn the number of documents that had a filter match.
1
2
# num of documents that matched filter query
print ("matched_count:", result.matched_count)

Confirm the identity of the MongoDB documents were changed by the API call replace_one()

  • Do a pymongo.results.UpdateResult object parsing to learn about those MongoDB documents modifed or deleted by the replace_one() API call.

Screenshot of Python IDLE making replace_one() API call in PyMongo and parsing the results object

Replace multiple data fields by using key-value pairs

  • To the dictionary object, add as many key-value pairs that you need for the field data you want to replace.

Here’s an example:

1
2
3
4
5
replacement_data = {
    "some date" : datetime.datetime.now(),
    "some text" : "ObjectRocket services",
    "some num" : 1234
}
  • A new data field is a key and the field data of the document is the value.

Update the document’s date and timestamp using the datetime() method

  • Pass the datetime.datetime.now() method to get the current date and time you made an API call for a document query.

  • The example here shows the "some date" field where the datetime.datetime.now() method is passed.

1
2
3
4
5
6
7
8
9
# query the same document _id again
query = {"_id" : ObjectId("5cfa4c0ad9edff487939dda5") }

# add "date" and "number" key-value pairs to the data
replacement_data = {
    "some date" : datetime.datetime.now(),
    "some text" : "ObjectRocket services",
    "some num" : 1234
}

>NOTE: MongoDB notices "some num" and as integers and places them as such. It’s also good to know that MongoDB puts new fields in a document if they are in your API method call, such as when using replace_one. The fields they insert don’t have to be in the original document.

Confirm that PyMongo replaced fields with MongoDB Compass IU

  • Use the MongoDB Compass IU to verify that the replace_one() method call’s actions were successful.

Screenshot of MongoDB Compass UI verifying that a document had its data replaced by the PyMongo driver

Use the “upsert” flag option to insert a document if none exists

  • The upsert flag option inserts a new document into a collection. The new document it inserts is the match returned from the filter query. However, if it didn’t return a match, then the data it uses for the document is the same replacement data that was passed from the replace_one() method.
1
query = {"_id" : "I don't exist" }
  • The upsert option uses the dictionary key of the query to base the new MongoDB document. For instance, the _id of an inserted document would be the same as the "_id" dictionary key of the query.

  • The example below uses the upsert option of the replace_one() method.

1
2
3
4
5
6
7
8
9
replacement_data = {
    "some date" : datetime.datetime.now(),
    "some text" : "ObjectRocket ROCKS!",
    "some num" : 42
    "some time" : time.time()
}

# 3 parameters passed: filter, replacement, and options
result = col.replace_one( query, replacement_data, upsert=True )

>NOTE: MongoDB calls"some time", the epoch seconds of time field "some time", a Double precision float. See “A positive verification of an inserted document from the result.upserted_id object” in the next section for an example of it in action.

  • Confirm that a upserted document was successful by getting the upserted_id attribute of the Results object.
1
2
# check for any new upserted IDs
print ("\nupserted_id:", result.upserted_id)
  • A value of None for the result.upserted_id object means that nothing was inserted.

A positive verification of an inserted document from the result.upserted_id object

  • The Compass UI of MongoDB displays the "some time" field and it shows a document number. MongoDB identifies the field as a Double precision float. The upserted _id was used as an option in replace_one.

Screenshot of MongoDB Compass UI verifying that a document was upserted by replace_one with PyMongo

Conclusion

This tutorial explained how to find MongoDB documents Python and replace MongoDB documents Python with the replace_one method. You also learned how to use the upsert flag option of the replace_one method to insert a document in a collection. You discovered how to create a filter dictionary, a requirement for API calls when you write MongoDB documents Python replace_one method scripts. We reviewed the replacement_data dictionary object and more. Use the examples as a reference and write documents PyMongo and replace documents PyMongo anytime you wish.

Just the Code

Here’s the sample code to modify MongoDB documents Python and replace MongoDB documents PyMongo with the replace_one() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

# import the datetime and time library
import datetime, time

# import the MongoClient class of the PyMongo library
from pymongo import MongoClient

# import ObjectID from MongoDB's BSON library
# (use pip3 to install bson)
from bson import ObjectId

# create a client instance of the MongoClient class
mongo_client = MongoClient('mongodb://localhost:27017')

# create database and collection instances
db = mongo_client["Some-Database"]
col = db["Some Collection"]

# check if collection has documents
total_docs = col.count_documents( {} )
print (col.name, "has", total_docs, "total documents.")


"""
REPLACING ALL OF A MONGODB DOCUMENT'S DATA
USING PYMONGO'S replace_one() METHOD
"""

# create filter query to replace a document
query = {"_id" : ObjectId("5cfa4c0ad9edff487939dda5") }

# add "date" and "number" key-value pairs to the data
replacement_data = {
    "some date" : datetime.datetime.now(),
    "some text" : "ObjectRocket services",
    "some num" : 1234
}

# pass dict objects to PyMongo's replace_one() method
result = col.replace_one( query, replacement_data, upsert=True )
print ("raw:", result.raw_result)
print ("acknowledged:", result.acknowledged)
print ("matched_count:", result.matched_count)


# create another filter query for a different document
query = {"_id" : "I don't exist" }

# data for replace_one() method with timestamp
replacement_data = {
    "some date" : datetime.datetime.now(),
    "some text" : "ObjectRocket ROCKS!",
    "some num" : 42
    "some time" : time.time()
}

# 3 parameters passed: filter, replacement, and options
result = col.replace_one( query, replacement_data, upsert=True )

# check for any new upserted IDs
print ("\nupserted_id:", result.upserted_id)

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.