- Trending Categories
- 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
Opposite of $addToSet to '$removeFromSet' in MongoDB?
To get the opposite of $addToSet to '$removeFromSet', use the $pull operator.
Let us create a collection with a document. The query to create a collection with a document is as follows −
> db.oppositeAddToSetDemo.insertOne({"StudentName":"John","StudentHobby":["Cricket","Cooking","Drawing"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8eddcc2f684a30fbdfd588") } > db.oppositeAddToSetDemo.insertOne({"StudentName":"Carol","StudentHobby":["Cricket","Dance","Hiking"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8eddfd2f684a30fbdfd589") } > db.oppositeAddToSetDemo.insertOne({"StudentName":"David","StudentHobby":["Learning","Photography"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ede272f684a30fbdfd58a") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.oppositeAddToSetDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8eddcc2f684a30fbdfd588"), "StudentName" : "John", "StudentHobby" : [ "Cricket", "Cooking", "Drawing" ] } { "_id" : ObjectId("5c8eddfd2f684a30fbdfd589"), "StudentName" : "Carol", "StudentHobby" : [ "Cricket", "Dance", "Hiking" ] } { "_id" : ObjectId("5c8ede272f684a30fbdfd58a"), "StudentName" : "David", "StudentHobby" : [ "Learning", "Photography" ] }
Here is the query for opposite of $addToSet to '$removeFromSet' using $pull operator −
> db.oppositeAddToSetDemo.update( ... {"StudentName": "John"}, ... {$pull: { "StudentHobby": "Cooking"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents from the collection using find(). The query is as follows:
> db.oppositeAddToSetDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8eddcc2f684a30fbdfd588"), "StudentName" : "John", "StudentHobby" : [ "Cricket", "Drawing" ] } { "_id" : ObjectId("5c8eddfd2f684a30fbdfd589"), "StudentName" : "Carol", "StudentHobby" : [ "Cricket", "Dance", "Hiking" ] } { "_id" : ObjectId("5c8ede272f684a30fbdfd58a"), "StudentName" : "David", "StudentHobby" : [ "Learning", "Photography" ] }
Advertisements