Create Collection
Starting from the MongoDB shell, we are creating a new collection “Dummy” in our MongoDB with the help of the command below: the createCollection() method.
{ ok: 1 }
Insert Documents
It is time to add documents to the MongoDB collection. For this, the MongoDB command below has been executed that is inserting multiple documents into the “Dummy” collection: insertMany() function. The documents contain information about cities, countries, and a count field (with values for some of the documents). Each document in the array has a set of key-value pairs. The command returns a response that the insertion is acknowledged.
... {city: "Los Angeles", country: "America", count: 2}, {city: "Italy", country: "France"},
... {city: "Istanbul", country: "Turkey", count: 8}, {city: "Delhi", country: "India", count: 7} ])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("63c7b3588083bbf655d69684"),
'1': ObjectId("63c7b3588083bbf655d69685"),
'2': ObjectId("63c7b3588083bbf655d69686"),
'3': ObjectId("63c7b3588083bbf655d69687"),
'4': ObjectId("63c7b3588083bbf655d69688")
}}
Display Documents
Now, to retrieve and display all the documents from the “Dummy” collection, we will be casting off the find() method in the instruction shown below. The returned documents are represented in an array format, with each record in the array as an object. The fields in each document include “_id”, “city”, “country”, and “count” i.e. “_id” field is a unique identifier assigned by MongoDB.
[
{ _id: ObjectId("63c7b3588083bbf655d69684"), city: 'Texas', country: 'England', count: 5 },
{ _id: ObjectId("63c7b3588083bbf655d69685"), city: 'Los Angeles', country: 'America', count: 2 },
{ _id: ObjectId("63c7b3588083bbf655d69686"), city: 'Italy', country: 'France' },
{ _id: ObjectId("63c7b3588083bbf655d69687"), city: 'Istanbul', country: 'Turkey', count: 8 },
{ _id: ObjectId("63c7b3588083bbf655d69688"), city: 'Delhi', country: 'India', count: 7 }
]
Example 01: ReplaceOne Method
The replaceOne method is used to replace a single document that matches a specified filter in MongoDB. Therefore, we will be using it in the instruction below to replace a document within the “Dummy” collection. The first argument passed to the replaceOne method is the filter. In this case, the filter is {“city”: “Delhi”}, which means that the document with the “city” field set to “Delhi” will be replaced. The second argument passed to the replaceOne method is the replacement document, which is the new document that will replace the old one: {“country”: “India-Pacific”}. Thus, the document with the “city” field set to “Delhi” will now have the “country” field set to “India-Pacific” instead of its previous value.
The code is wrapped in a try-catch block, which is used to handle any errors that may occur during the execution of the replaceOne method. If an error occurs, it will be caught by the catch block and printed to the console using the print() function. The output shows that one document has been matched, modified, and the upserted count is zero.
... db.Dummy.replaceOne( {"city": "Delhi"}, {"country": "India-Pacific"});
... } catch(e) { print(e); }
{ {
acknowledged: true,c7b3588083bbf655d69684"),
insertedId: null,
matchedCount: 1,and',
modifiedCount: 1,
upsertedCount: 0
} }
After displaying all the documents from the “Dummy” collection on the shell using the “find” function, we have to know that the 5th record has been updated with “country: ‘India-Pacific’”.
[
{ _id: ObjectId("63c7b3588083bbf655d69684"), city: 'Texas', country: 'England', count: 5 },
{ _id: ObjectId("63c7b3588083bbf655d69685"), city: 'Los Angeles', country: 'America', count: 2 },
{ _id: ObjectId("63c7b3588083bbf655d69686"), city: 'Italy', country: 'France' },
{ _id: ObjectId("63c7b3588083bbf655d69687"), city: 'Istanbul', country: 'Turkey', count: 8 },
{ _id: ObjectId("63c7b3588083bbf655d69688"), country: 'India-Pacific' }
]
Example # 02: ReplaceOne Method With Upsert Option
In this code example, we will be making use of the upsert option in the replaceOne() method that adds a new record if the specified one is not found. Therefore, the code we have been using below includes an option for upserting the document. The first argument handed to the replaceOne method is the filter {“city”: “Mali”}: the document with the “city” field set to “Mali” will be replaced. The second argument is the replacement document { city: “Mali”, country: “Maldives”, count: 5 }. The “city” field set to “Mali” will now have the “country” field set to “Maldives” and the “count” set to 5.
The third argument passed to the replaceOne method is the option {upsert: true}: to insert a whole new document if not found. The code is wrapped in a try-catch block once again to print() the error caught in the command. The response result shows that no documents have been matched and modified but one document has been upserted: a new document is inserted since the document specified in the filter did not exist.
... { city: "Mali", country: "Maldives", count: 5 }, {upsert: true});
... } catch (e) {print(e);}
{
acknowledged: true,
insertedId: ObjectId("63c7bfaaf8c41df4b034b120"),
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 1
}
To confirm the insertion of one extra record, we have displayed the whole “Dummy” collection and have the result shown below. The upsert option has inserted a new document at the end.
[
{ _id: ObjectId("63c7b3588083bbf655d69684"), city: 'Texas', country: 'England', count: 5 },
{ _id: ObjectId("63c7b3588083bbf655d69685"), city: 'Los Angeles', country: 'America', count: 2 },
{ _id: ObjectId("63c7b3588083bbf655d69686"), city: 'Italy', country: 'France' },
{ _id: ObjectId("63c7b3588083bbf655d69687"), city: 'Istanbul', country: 'Turkey', count: 8 },
{ _id: ObjectId("63c7b3588083bbf655d69688"), city: 'Delhi', country: 'India', count: 7 }
{ _id: ObjectId("63c7bfaaf8c41df4b034b120"), city: 'Mali', country: 'Maldives', count: 5 }
]
Example # 03: ReplaceAll Method
Here is the illustration on how the replaceAll() operator works in MongoDB. The input for the $replaceAll operator is the “country” field from the documents in the collection. The “find” value is “i” and the replacement value is “e”. This means that all occurrences of the letter “i” in the “country” field will be replaced with the letter “e”. The result is a new “country” field with the modified string. For example, the original value “India-Pacific” would be replaced with “Indea-Pacefec”, the value “America” is now “Amereca”, and “Maldives” is now “Maldeves” as demonstrated in the output as well.
[
{ _id: ObjectId("63c7b3588083bbf655d69684"), country: 'England' },
{ _id: ObjectId("63c7b3588083bbf655d69685"), country: 'Amereca' },
{ _id: ObjectId("63c7b3588083bbf655d69686"), country: 'France' },
{ _id: ObjectId("63c7b3588083bbf655d69687"), country: 'Turkey' },
{ _id: ObjectId("63c7b3588083bbf655d69688"), country: 'Indea-Pacefec' },
{ _id: ObjectId("63c7bfaaf8c41df4b034b120"), country: 'Maldeves' }
]
Let us update the above illustration once again. The “find” argument has been passed with a value “a” and the replacement value is “*****”. This means that all occurrences of the letter “a” in the “city” field will be replaced with the string “******”. The result is a new “city” field with the modified string. For example, the original “Texas” would be replaced with “Tex*****s”, and the original “Italy” would be replaced with “It*****ly” and so on.
[
{ _id: ObjectId("63c7b3588083bbf655d69684"), city: 'Tex******s' },
{ _id: ObjectId("63c7b3588083bbf655d69685"), city: 'Los Angeles' },
{ _id: ObjectId("63c7b3588083bbf655d69686"), city: 'It******ly' },
{ _id: ObjectId("63c7b3588083bbf655d69687"), city: 'Ist******nbul' },
{ _id: ObjectId("63c7b3588083bbf655d69688"), city: null },
{ _id: ObjectId("63c7bfaaf8c41df4b034b120"), city: 'M******li' }
]
Conclusion
We have defined the replaceOne() and replaceAll() functions along with the difference between them. We have explained 3 of the distinct examples in the article i.e. replaceOne() method to update a single field, the upsert option to be used in the replaceOne method to add a new record if not found a matching field and the replaceAll() method to replace a string in all documents. The replaceOne() method is very different from the replaceAll method when it comes to the effect it adds to the database collection.