使用UPDATE更新并使用SET设置新值。让我们创建一个包含文档的集合-
> db.demo34.insertOne({"StudentFirstName":"Chris","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e1758b4cfb11e5c34d898cd") } > db.demo34.insertOne({"StudentFirstName":"David","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5e1758bdcfb11e5c34d898ce") } > db.demo34.insertOne({"StudentFirstName":"Bob","StudentAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5e1758c6cfb11e5c34d898cf") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo34.find();
这将产生以下输出-
{ "_id" : ObjectId("5e1758b4cfb11e5c34d898cd"), "StudentFirstName" : "Chris", "StudentAge" : 24 } { "_id" : ObjectId("5e1758bdcfb11e5c34d898ce"), "StudentFirstName" : "David", "StudentAge" : 23 } { "_id" : ObjectId("5e1758c6cfb11e5c34d898cf"), "StudentFirstName" : "Bob", "StudentAge" : 20 }
以下是更新MongoDB行的查询-
> db.demo34.update({_id:ObjectId("5e1758bdcfb11e5c34d898ce")}, ... {$set:{"StudentFirstName" : "Mike","StudentAge" : 19}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo34.find();
这将产生以下输出-
{ "_id" : ObjectId("5e1758b4cfb11e5c34d898cd"), "StudentFirstName" : "Chris", "StudentAge" : 24 } { "_id" : ObjectId("5e1758bdcfb11e5c34d898ce"), "StudentFirstName" : "Mike", "StudentAge" : 19 } { "_id" : ObjectId("5e1758c6cfb11e5c34d898cf"), "StudentFirstName" : "Bob", "StudentAge" : 20 }