
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
Toggle Query in MongoDB
You need to find the document and after that you need to use update to toggle query. Let us first create a collection with documents −
> db.toggleDemo.insertOne({"CustomerName":"John Smith","CustomerAge":28,"isMarried":true}); { "acknowledged" : true, "insertedId" : ObjectId("5cc7be138f9e6ff3eb0ce43b") } > db.toggleDemo.insertOne({"CustomerName":"David Miller","CustomerAge":25,"isMarried":false}); { "acknowledged" : true, "insertedId" : ObjectId("5cc7be2e8f9e6ff3eb0ce43c") }
Following is the query to display all documents from a collection with the help of find() method −
> db.toggleDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc7be138f9e6ff3eb0ce43b"), "CustomerName" : "John Smith", "CustomerAge" : 28, "isMarried" : true } { "_id" : ObjectId("5cc7be2e8f9e6ff3eb0ce43c"), "CustomerName" : "David Miller", "CustomerAge" : 25, "isMarried" : false }
Toggle query in MongoDB −
> var value = db.toggleDemo.findOne({CustomerName:"David Miller"}); > db.toggleDemo.update({CustomerName:"David Miller"}, {$set: {isMarried: !value.isMarried}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document with isMarried:false has been toggled with value true. We will now display all documents from the collection −
> db.toggleDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc7be138f9e6ff3eb0ce43b"), "CustomerName" : "John Smith", "CustomerAge" : 28, "isMarried" : true } { "_id" : ObjectId("5cc7be2e8f9e6ff3eb0ce43c"), "CustomerName" : "David Miller", "CustomerAge" : 25, "isMarried" : true }
Advertisements