您需要将$set运算符与upsert:true一起使用。首先让我们创建一个包含文档的集合-
> db.updateWithUpsertDemo.insertOne({"StudentFirstName":"John","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a61c345990cee87fd890") } > db.updateWithUpsertDemo.insertOne({"StudentFirstName":"Larry","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a624345990cee87fd891") } > db.updateWithUpsertDemo.insertOne({"StudentFirstName":"David","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cd2a62c345990cee87fd892") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.updateWithUpsertDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd2a61c345990cee87fd890"), "StudentFirstName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5cd2a624345990cee87fd891"), "StudentFirstName" : "Larry", "StudentAge" : 23 } { "_id" : ObjectId("5cd2a62c345990cee87fd892"), "StudentFirstName" : "David", "StudentAge" : 24 }
以下是结合了更新和查询部分以形成上色文档的查询-
> db.updateWithUpsertDemo.update({_id: ObjectId("5cd2a624345990cee87fd891")},{"$set": {"StudentFirstName": "Chris"}}, {upsert:true}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们检查字段“ StudentFirstName”是否已更改-
> db.updateWithUpsertDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd2a61c345990cee87fd890"), "StudentFirstName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5cd2a624345990cee87fd891"), "StudentFirstName" : "Chris", "StudentAge" : 23 } { "_id" : ObjectId("5cd2a62c345990cee87fd892"), "StudentFirstName" : "David", "StudentAge" : 24 }