将更新和查询部分组合起来以在 MongoDB 中构成更新的文档?
你需要将 $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 }
广告