Modify sequence in MongoDB


To modify a sequence, use findAndModify(). Let us create a collection with documents −

> db.demo261.insertOne({_id:100,Name:"Chris"});
{ "acknowledged" : true, "insertedId" : 100 }

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

> db.demo261.find();

This will produce the following output −

{ "_id" : 100, "Name" : "Chris" }

Following is the query to modify sequence −

> db.demo262.insert({_id:"newId",sequence_value:0})
WriteResult({ "nInserted" : 1 })
> function getNext(sName){
...
...   var d= db.demo262.findAndModify({
...      query:{_id: sName},
...      update: {$inc:{sequence_value:1}},
...      new:true
...   });
...   return d.sequence_value;
...}

Following is the query to call the above function to generate the sequence in MongoDB −

> db.demo261.insert({
...   "_id":getNext("newId"),
...   "Name":"Chris"
... })
WriteResult({ "nInserted" : 1 })
> db.demo261.insert({    "_id":getNext("newId"),   "Name":"Bob" })
WriteResult({ "nInserted" : 1 })

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

> db.demo261.find();

This will produce the following output −

{ "_id" : 100, "Name" : "Chris" }
{ "_id" : 1, "Name" : "Chris" }
{ "_id" : 2, "Name" : "Bob" }

Updated on: 31-Mar-2020

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements