在MongoDB嵌套对象中增加一个值?
要增加嵌套对象中的值,可以使用$inc运算符。让我们首先实现以下查询以创建包含文档的集合
>db.incrementValueDemo.insertOne({"StudentName":"Larry","StudentCountryName":"US","StudentDetails":[{"StudentSubjectName":"Math","StudentMathMarks":79}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c986ca0330fd0aa0d2fe4a2")
}以下是在find()方法的帮助下显示集合中所有文档的查询
> db.incrementValueDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
"StudentName" : "Larry",
"StudentCountryName" : "US",
"StudentDetails" : [
{
"StudentSubjectName" : "Math",
"StudentMathMarks" : 79
}
]
}以下是增加嵌套对象中的值的查询。标记将在此处递增
> db.incrementValueDemo.update( {"StudentDetails.StudentSubjectName":"Math"}, { $inc : {
"StudentDetails.$.StudentMathMarks" : 1 } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })以下是查询值是否增加的查询
> db.incrementValueDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
"StudentName" : "Larry",
"StudentCountryName" : "US",
"StudentDetails" : [
{
"StudentSubjectName" : "Math",
"StudentMathMarks" : 80
}
]
}