Wednesday, October 2, 2019

MongoDB - Update Documents

Click the link: "MongoDB - Update Documents"

In this MongoDB tutorial we will learn to update documents.
Login to your MongoDB server and insert the following documents.
For this tutorial I will insert the documents in the subscription collection.
> db.subscription.insertMany([
  {
    "firstname": "John",
    "lastname": "Doe",
    "uid": 1,
    "accountstatus": "ACTIVE",
    "plan": "TRIAL15DAYS",
    "modifiedAt": null,
    "createdAt": new Date()
  },
  {
    "firstname": "Jane",
    "lastname": "Doe",
    "uid": 2,
    "accountstatus": "ACTIVE",
    "plan": "PLAN30DAYS",
    "modifiedAt": null,
    "createdAt": new Date()
  },
  {
    "firstname": "Jim",
    "lastname": "Doe",
    "uid": 3,
    "accountstatus": "SUSPENDED",
    "plan": "PLAN60DAYS",
    "modifiedAt": null,
    "createdAt": new Date()
  },
  {
    "firstname": "Alice",
    "lastname": "Doe",
    "uid": 4,
    "accountstatus": "ACTIVE",
    "plan": "PLAN1YEAR",
    "modifiedAt": null,
    "createdAt": new Date()
  }
])
Note! We are using new Date() to set the createdAt to current date time.

Update one document

To update a single document we use updateOne method.

Syntax

db.collectionName.updateOne(filter, update)
Where, filter is the condition to get the required document and update is the part of the document we want to update.
In the following example we are updating the account status of user having uid equal to 3 from SUSPENDED to ACTIVE.
> db.subscription.updateOne(
  { "uid": 3 },
  {
    $set: { "accountstatus": "ACTIVE" },
    $currentDate: { "modifiedAt": true }
  }
)
We use $set operator to update the value of accountstatus.
We use $currentDate operator to set the modifiedAt to current date.
If we now fetch the above document we will get the following.
> db.subscription.find({ "uid": 3 }).pretty()

{
  "_id" : ObjectId("5d7715d5b385796f53d4c8ff"),
  "firstname" : "Jim",
  "lastname" : "Doe",
  "uid" : 3,
  "accountstatus" : "ACTIVE",
  "plan" : "PLAN60DAYS",
  "modifiedAt" : ISODate("2019-09-10T03:18:42.406Z"),
  "createdAt" : ISODate("2019-09-10T03:17:41.130Z")
}

Read more...

No comments:

Post a Comment