在嵌入的MongoDB文件中增加一个字段?
假设,在这里,我们在StudentDetails内部增加了MongoDB的StudentScores-
... "StudentScores": { ... "StudentMathScore": 90, ... "StudentMongoDBScore": 78 ... }
首先让我们创建一个包含文档的集合-
> db.embeddedValueIncrementDemo.insertOne( ... { ... "StudentDetails": { ... "StudentScores": { ... "StudentMathScore": 90, ... "StudentMongoDBScore": 78 ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2b670345990cee87fd896") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.embeddedValueIncrementDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd2b670345990cee87fd896"), "StudentDetails" : { "StudentScores" : { "StudentMathScore" : 90, "StudentMongoDBScore" : 78 } } }
以下是增加嵌入值的查询。在这里,我们增加了StudentMongoDBScore-
> db.embeddedValueIncrementDemo.update({ _id: new ObjectId("5cd2b670345990cee87fd896") }, { $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } }, { upsert: true, safe: true }, null); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查所有文件-
> db.embeddedValueIncrementDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd2b670345990cee87fd896"), "StudentDetails" : { "StudentScores" : { "StudentMathScore" : 90, "StudentMongoDBScore" : 98 } } }