在 MongoDB 中更新某个值,而不同的键等于某个值?
让我们使用文档创建一个集合 −
> db.demo196.insertOne( ... { ... ... "Id" : "101", ... "details" : [ ... { ... "FirstName" : "Chris", ... "LastName" : "Brown", ... "Score" : 45 ... }, ... { ... "FirstName" : "David", ... "LastName" : "Miller", ... "Score" : 87 ... }, ... { ... "FirstName" : "John", ... "LastName" : "Doe", ... "Score" : 56 ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : ObjectId("5e3af6b103d395bdc21346d7") }
使用 find() 方法从集合中显示所有文档 −
> db.demo196.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3af6b103d395bdc21346d7"), "Id" : "101", "details" : [ { "FirstName" : "Chris", "LastName" : "Brown", "Score" : 45 }, { "FirstName" : "David", "LastName" : "Miller", "Score" : 87 }, { "FirstName" : "John", "LastName" : "Doe", "Score" : 56 } ] }
以下是对不同键等于某个值时更新键值内容的查询 −
> db.demo196.update({"details":{"$elemMatch":{"FirstName" : "David", "LastName" : "Miller"}}}, ... {"$set":{"details.$.Score":98}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
使用 find() 方法从集合中显示所有文档 −
> db.demo196.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3af6b103d395bdc21346d7"), "Id" : "101", "details" : [ { "FirstName" : "Chris", "LastName" : "Brown", "Score" : 45 }, { "FirstName" : "David", "LastName" : "Miller", "Score" : 98 }, { "FirstName" : "John", "LastName" : "Doe", "Score" : 56 } ] }
广告