“Toggle” query in MongoDB?

MongoDBDatabaseBig Data Analytics

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
}
raja
Published on 21-May-2019 15:27:25
Advertisements