"Toggle" query in MongoDB?

To implement a toggle query in MongoDB, you need to find the document first and then use the update operation to toggle the boolean field value. The toggle operation switches a boolean value from true to false or vice versa.

Let us first create a collection with sample 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
}

Implementing Toggle Query

To toggle a boolean field, we first retrieve the document using findOne(), then update the field by negating its current value using the logical NOT operator (!) −

> 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 verify that the document with isMarried:false has been toggled to 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
}

As you can see, David Miller's isMarried field has been successfully toggled from false to true. This technique is useful for switching boolean states in MongoDB documents efficiently.

Updated on: 2026-03-13T20:58:51+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements