在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 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短