在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
}
]
}热门推荐
10 预祝高尔夫的祝福语简短
11 进驻新居的祝福语简短
12 结业蛋糕男生祝福语简短
13 生日祝福语短句简短霸气
14 新年探亲祝福语简短精辟
15 祝福语简短唯美10字
16 公司年终晚会祝福语简短
17 给儿子生日祝福语 简短
18 男友红包祝福语简短精辟