MongoDB query to add timestamp only if it is not present


For this, use upsert and multi in MongoDB −

Upsert − If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.

Multi − f set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false.

Let us create a collection with documents −

> db.demo479.insertOne({"DueDate":new ISODate("2020-01-10"),"Name":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e820733b0f3fa88e2279094")
}
> db.demo479.insertOne({"Name":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e820748b0f3fa88e2279095")
}
> db.demo479.insertOne({"DueDate":new ISODate("2019-12-31"),"Name":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e82075fb0f3fa88e2279096")
}
> db.demo479.insertOne({"Name":"Carol"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e820767b0f3fa88e2279097")
}

Display all documents from a collection with the help of find() method −

> db.demo479.find();

This will produce the following output −

{ "_id" : ObjectId("5e820733b0f3fa88e2279094"), "DueDate" : ISODate("2020-01-
10T00:00:00Z"), "Name" : "Chris" }
{ "_id" : ObjectId("5e820748b0f3fa88e2279095"), "Name" : "David" }
{ "_id" : ObjectId("5e82075fb0f3fa88e2279096"), "DueDate" : ISODate("2019-12-
31T00:00:00Z"), "Name" : "Bob" }
{ "_id" : ObjectId("5e820767b0f3fa88e2279097"), "Name" : "Carol" }

Following is the query to add timestamp field only if it not present −

> db.demo479.update({DueDate:{$exists:false}}, {$set : {"DueDate":new Date}}, {upsert:false,
multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Display all documents from a collection with the help of find() method -

> db.demo479.find();

This will produce the following output −

{ "_id" : ObjectId("5e820733b0f3fa88e2279094"), "DueDate" : ISODate("2020-01-
10T00:00:00Z"), "Name" : "Chris" }
{ "_id" : ObjectId("5e820748b0f3fa88e2279095"), "Name" : "David", "DueDate" :
ISODate("2020-03-30T14:52:29.656Z") }
{ "_id" : ObjectId("5e82075fb0f3fa88e2279096"), "DueDate" : ISODate("2019-12-
31T00:00:00Z"), "Name" : "Bob" }
{ "_id" : ObjectId("5e820767b0f3fa88e2279097"), "Name" : "Carol", "DueDate" :
ISODate("2020-03-30T14:52:29.656Z") }

Updated on: 11-May-2020

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements