Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }Advertisements