Update Data in MongoDB

Deployment Type:
Client:

    Author: MongoDB Documentation Team

    In this guide, you will update documents in a MongoDB database.

    Time required: 10 minutes

    What You’ll Need

    • Warning

      If you are running MongoDB locally and have not enabled authentication, your MongoDB instance is not secure.

    • Complete the Import Data into MongoDB guide so that there is data in your database to update.

    Procedure

    1

    Connect to your MongoDB instance.

    Select the operating system platform on which you are running the MongoDB client you have selected.

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo.exe <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    If you wish to manually configure your Compass connection, load Compass and select the New Connection link. You will see a form where you can enter connection information for MongoDB.

    Atlas users can copy a URI string from the Atlas console into Compass. MongoDB Compass can detect whether you have a MongoDB URI connection string in your system clipboard and auto- populate the connection dialog from the URI.

    See Set Up Atlas Connectivity for information on how to get the Atlas connection string URI into your copy buffer.

    If Compass was already running when you copied the URI string, click the NEW CONNECTION button.

    ../../_images/connect-to-host.png

    You will be prompted to populate the connection dialog. Click Yes.

    You should then populate the password field with the proper password for your MongoDB user in the connection form.

    Note

    Errors related to connecting through Compass will appear in red at the top of the Connect screen.

    It’s a good idea to put your connection code in a class so that it can be reused.

    from pymongo import MongoClient
    
    class Connect(object):
        @staticmethod    
        def get_connection():
            return MongoClient("<URISTRING>")
    

    If your connection_string starts with mongodb+srv, you need to install the dnspython module with

    python -m pip install dnspython
    

    Now add code to call the class you just created.

    from connect import Connect
    from pymongo import MongoClient
    
    connection = Connect.get_connection()
    
        final String uriString = "<URISTRING>";
        MongoClientURI uri = new MongoClientURI(uriString);
        MongoClient mongoClient = new MongoClient(uri);
    
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    
    // Connection URL
    const url = '<URISTRING>';
    
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, client) {
      assert.equal(null, err);
      client.close();
    });
    

    The asyncio and pprint imports will be used as you add functionality to your example code.

    import motor.motor_asyncio
    import asyncio
    import pprint
    
    client = motor.motor_asyncio.AsyncIOMotorClient('<URISTRING>')
    

    The MongoDB.Bson package is used in CRUD operations, so you’ll import it here.

    using System;
    using MongoDB.Bson;
    using MongoDB.Driver;
    
    namespace csharptest
    {
        class Connect
        {
            static void Main(string[] args)
            {
               var client = new MongoClient("<URISTRING>");
            }
        }
    }
    
    2

    Switch to the test database.

    In this guide, you will update documents in a collection in the test database.

    To switch to the test database in the mongo shell, type

    use test
    

    If the database has not been created already, click the Create Database button.

    Screeenshot after connecting with the "Create Database" button.

    Select the test database on the left side of the Compass interface. Compass will list all of the collections in the database below the database name.

    Screenshot of the MongoDB Compass UI showing with the "test" database selected in the list of databases in the cluster.

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    MongoDatabase mongoDB = mongoClient.getDatabase("test");
    MongoCollection<Document> collection = mongoDB.getCollection("inventory");
    

    Within the connect block, set db to the test database.

    const db = client.db("test");
    

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    var database = client.GetDatabase("test");
    var collection = database.GetCollection<BsonDocument>("inventory");
    
    3

    Update a single document in the inventory collection.

    To change a field value, MongoDB provides update operators to modify values. Some update operators, including will create the specified field if the field does not exist in the document.

    The following operation updates the first document with item equal to paper. The operation uses:

    • $set to update the status field and the uom field embedded in the size document. To access the fields within embedded documents, the operation uses dot notation.
    • $currentDate to set the lastModified field to the current date.
    db.inventory.updateOne(
        { "item" : "paper" }, // specifies the document to update
        {
          $set: {  "size.uom" : "cm",  "status" : "P" },
          $currentDate: { "lastModified": true }
        }
    )
    
    1. Copy the following filter into the Compass query bar and click Find:

      { "item" : "paper" }
      
    2. Click the edit icon on the first document returned:

      Screenshot of the MongoDB Compass interface searching for documents in the inventory collection in the test database where the "item" field value is "paper". One document is displayed.
    3. Expand the size field and update the uom value to cm. Click inside the status field and click the plus button, then click Add field after status. Add a lastModified field, select Date as its type using the drop-down menu on the right, and input today’s date:

      Screenshot of the MongoDB Compass interface where the first returned document has been edited to change the size.uom field value to "cm" and add a lastModified date field with value 2018-04-17.
    4. Click Update.

      Screenshot of the MongoDB Compass interface where the "Update" button is selected to finalize the changes made to a document.
    • $set to update the status field and the uom field embedded in the size document. To access the fields within embedded documents, the operation uses dot notation.
    • :$currentDate to set the lastModified field to the current date.
    db.inventory.update_one(
        {"item": "paper"},
        {"$set": {"size.uom": "cm", "status": "P"},
         "$currentDate": {"lastModified": True}})
    

    Run the loop:

    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_update_one())
    
    • set to update the status field and the uom field embedded in the size document. To access the fields within embedded documents, the operation uses dot notation.
    • currentDate to set the lastModified field to the current date.
    collection.updateOne(eq("item", "paper"),
            combine(set("size.uom", "cm"), set("status", "P"), currentDate("lastModified")));
    
    db.collection('inventory').updateOne(
      { item: "paper" },
      { $set: { "size.uom": "cm", status: "P" },
        $currentDate: { lastModified: true } })
    .then(function(result) {
      // process result
    })            
    
    • $set to update the status field and the uom field embedded in the size document. To access the fields within embedded documents, the operation uses dot notation.
    • :$currentDate to set the lastModified field to the current date.
    • $set to update the status field and the uom field embedded in the size document. To access the fields within embedded documents, the operation uses dot notation.
    • $currentDate to set the lastModified field to the current date.
    await db.inventory.update_one(
        {"item": "paper"},
        {"$set": {"size.uom": "cm", "status": "P"},
         "$currentDate": {"lastModified": True}})
    

    For completeness, the following example shows how you might wrap the update one operation with the asyncio event loop:

    async def do_update_one():
        document = await db.inventory.update_one(
                       {"item": "paper"},
                       {"$set": {"size.uom": "cm", "status": "P"},
                        "$currentDate": {"lastModified": True}})
        pprint.pprint(document.raw_result)
    
    var filter = Builders<BsonDocument>.Filter.Eq("item", "paper");
    var update = Builders<BsonDocument>.Update.Set("size.uom", "cm").Set("status", "P").CurrentDate("lastModified");
    var result = collection.UpdateOne(filter, update);
    
    4

    Update multiple documents.

    The following operation updates all of the documents with quantity value less than 50.

    db.inventory.updateMany(
        { "qty" : { $lt: 50 } }, // specifies the documents to update
        {
           $set: { "size.uom" : "cm", "status": "P" },
           $currentDate : { "lastModified": true }
        }
    )
    
    1. Copy the following filter into the Compass query bar and click Find:

      { "qty" : { $lt: 50 } }
      
    2. For each document, click the edit icon:

      Screenshot of the MongoDB Compass UI with a filter for all documents where the qty field values is less than 50. The edit button is moused over for the first returned document.
    3. Make the following changes:

      • Expand the size field and update the uom value to cm.
      • Change the value of the status field to P.
      • Click inside the status field and click the plus button, then click Add field after status. Add a lastModified field, select Date as its type using the drop-down menu on the right, and input today’s date:
      Screenshot of the MongoDB Compass interface where the first returned document has been edited to change the status field value to P and add a lastModified date field with value 2018-04-17.
    4. Click Update.

    db.inventory.update_many(
        {"qty": {"$lt": 50}},
        {"$set": {"size.uom": "in", "status": "P"},
         "$currentDate": {"lastModified": True}})
    
    collection.updateMany(lt("qty", 50),
            combine(set("size.uom", "in"), set("status", "P"), currentDate("lastModified")));
    
    db.collection('inventory').updateMany(
      { qty: { $lt: 50 } },
      { $set: { "size.uom": "in", status: "P" },
        $currentDate: { lastModified: true } })
    .then(function(result) {
      // process result
    })            
    
    await db.inventory.update_many(
        {"qty": {"$lt": 50}},
        {"$set": {"size.uom": "in", "status": "P"},
         "$currentDate": {"lastModified": True}})
    

    For completeness, the following example shows how you might wrap the update many operation with the asyncio event loop:

    async def do_update_many():
        document = await db.inventory.update_many(
                       {"qty": {"$lt": 50}},
                       {"$set": {"size.uom": "in", "status": "P"},
                        "$currentDate": {"lastModified": True}})
        pprint.pprint(document.raw_result)
    

    Run the asyncio loop to execute both the update_one and update_many operations:

    loop = asyncio.get_event_loop()
    
    tasks = [
        asyncio.ensure_future(do_update_one()),
        asyncio.ensure_future(do_update_many()),
    ]
    
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()
    
    var filter = Builders<BsonDocument>.Filter.Lt("qty", 50);
    var update = Builders<BsonDocument>.Update.Set("size.uom", "in").Set("status", "P").CurrentDate("lastModified");
    var result = collection.UpdateMany(filter, update);
    

    The operation returns a WriteResult document that contains the status of the operation:

    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    

    The operation returns an instance of pymongo.results.UpdateResult that contains the status of the operation.

    The operation returns an instance of com.mongodb.client.result.UpdateResult with the status of the operation.

    The operation returns a promise that provides a result containing the status of the operation.

    The operations asynchronously return instances of pymongo.results.UpdateResult that contains the status of the operation.

    Upon successful execution, the operation returns an instance of UpdateResult that contains the status of the operation.

    When you are done working with your MongoDB data, close your connection to MongoDB:

    mongoClient.close();
    

    Summary

    If you have successfully completed this guide, you have updated documents in MongoDB. In the next guide, you’ll see how to delete a document from a MongoDB collection.

    What’s Next

    In this guide, you will delete documents from a MongoDB database.