- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pull and add to set at the same time with MongoDB? Is it Possible?
Yes, you can use pull and add at the same time with $addToSet and $pull operator. Let us first create a collection with documents
> db.pullAndAddToSetDemo.insertOne({StudentScores : [78, 89, 90]} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c9a797e15e86fd1496b38af") }
Following is the query to display all documents from a collection with the help of find() method
> db.pullAndAddToSetDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9a797e15e86fd1496b38af"), "StudentScores" : [ 78, 89, 90 ] }
Following is the query to pull and addtoset at the same time in MongoDB
> var addAndPull = db.pullAndAddToSetDemo.initializeOrderedBulkOp(); > addAndPull.find({ "StudentScores": 89 }).updateOne({ "$addToSet": { "StudentScores": 99 } }); > addAndPull.find({ "StudentScores": 90 }).updateOne({ "$pull": { "StudentScores": 90 } }); > addAndPull.execute();
This will produce the following output
BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 0, "nUpserted" : 0, "nMatched" : 2, "nModified" : 2, "nRemoved" : 0, "upserted" : [ ] })
Let us check the document once again from the collection. Following is the query
> db.pullAndAddToSetDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9a797e15e86fd1496b38af"), "StudentScores" : [ 78, 89, 99 ] }
Advertisements