MongoDB 中的“切换”查询?
你需要找到文档,然后使用更新切换查询。我们首先创建一个带有文档的集合 -
> 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 })
让我们检查一下是已婚: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 }
广告