Updating Fields of document in MongoDB



  • MongoDB provides 4 key methods to update the document in the collection those are

    sno Method Description
    1 update() Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter.
    2 updateMany() Update all documents that match a specified filter.
    3 updateOne() Updates at most a single document that match a specified filter even though multiple documents may match the specified filter.
    4 replaceOne() Replaces at most a single document that match a specified filter even though multiple documents may match the specified filter.
    NOTE:
    1. All the methods will have the same signature except method names and its return concept.
    2. Means except of update() method other methods will acknowledge response with objectId.
    3. So I am mentioning update() syntax
    4. Please refer Update Operators section in this tutorial for better understanding.
    5. Please refer WildCard/RegEx section in this tutorial for better understanding.

    Syntax:
    db.collection.update(
    <query>, <update statement>,
    {upsert:<boolean>,
     multi: <boolean>,
     writeConcern: <document>
     })
    NOTE:
    1. Upsert:true will creates a new document when no document matches the query criteria.
    2. If we don’t use Field update operators ($set,$inc..) update statement will be replaced with matched ones.
Copyright © 2018-2020 TutorialToUs. All rights reserved.