MongoDB中的“切换”查询?
您需要找到文档,然后需要使用update来切换查询。首先让我们创建一个包含文档的集合-
> 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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.toggleDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7be138f9e6ff3eb0ce43b"), "CustomerName" : "John Smith", "CustomerAge" : 28, "isMarried" : true } { "_id" : ObjectId("5cc7be2e8f9e6ff3eb0ce43c"), "CustomerName" : "David Miller", "CustomerAge" : 25, "isMarried" : false }
在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 })
让我们使用isMarried:false检查文档是否已切换为true。现在,我们将显示集合中的所有文档-
> db.toggleDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7be138f9e6ff3eb0ce43b"), "CustomerName" : "John Smith", "CustomerAge" : 28, "isMarried" : true } { "_id" : ObjectId("5cc7be2e8f9e6ff3eb0ce43c"), "CustomerName" : "David Miller", "CustomerAge" : 25, "isMarried" : true }