I have a mongo document like this
{
"_id" : "2213",
"userId" : "99872",
"enterpriseId" : 13,
"courses" : [
{
"stateName" : "test program345",
"courseId" : "456",
"courseName" : "testCourse",
"duration" : 1,
"lag" : 0,
"courseType" : "3",
"scheduledStartDate" : ISODate("2019-07-02T10:16:22.000+05:30"),
"scheduledEndDate" : ISODate("2019-07-02T10:16:22.000+05:30"),
"transitionType" : "onComplete"
},
{
"stateName" : "test program3455",
"courseId" : "4",
"courseName" : "testCourse",
"duration" : 1,
"lag" : 0,
"courseType" : "2",
"transitionType" : "onComplete",
"scheduledStartDate" : ISODate("2019-07-08T17:07:13.479+05:30"),
"courseProgress" : 100
}
],
"userStatus" : 1,
"modified" : ISODate("2019-07-02T10:16:22.634+05:30"),
"created" : ISODate("2019-07-02T10:16:22.634+05:30"),
"completionStatus" : "IP"
}
I want to Update only those document where courseId is 4 and courseProgress is not exits and completionStatus is not equal to F.
我已经进行了此查询,但是即使courseProgress位于数组的第二个索引上,仍会更新文档
db.table.update({
'courses.courseId':'4',
'completionStatus':{$ne:'F'},
'courses':{$elemMatch:{'courseProgress':{$exists:false}}},
'enterpriseId':13},
{$set : {'courses.$.courseId' : '45','courses.$.courseName':'testCourse'}},{multi:true}
)
即使在数组的第二个索引上存在courseProgress,此查询仍会更新该字段。由于我是mongodb的新手,请帮助我解决这个问题。
答案 0 :(得分:1)
$
仅更新它在数组中匹配的第一个元素。要更新数组中所有匹配的元素,您需要使用$[]
。
尝试一下:
db.table.update({
'courses.courseId':'4',
'completionStatus':{$ne:'F'},
'courses':{$elemMatch:{'courseProgress':{$exists:false}}},
'enterpriseId':13},
{$set : {'courses.$[].courseId' : '45','courses.$[].courseName':'testCourse'}},{multi:true}
)
有关详细信息,请阅读$[] Mongo documentation