MongoDB数组元素更新查询不符合预期,请求技术支持
Let's break down what's going wrong with your current query and fix it to match your exact requirements.
Your Core Requirements
You need to update documents only when all these conditions are met:
- The
coursesarray contains an element withcourseId: "4"and that same element does not have acourseProgressfield - The document's
completionStatusis not"F" - The document's
enterpriseIdis13
Why Your Current Query Fails
Your existing query splits the courses array conditions into separate checks:
'courses.courseId':'4', 'courses':{$elemMatch:{'courseProgress':{$exists:false}}}
MongoDB interprets this as:
"Find documents where the
coursesarray has any element withcourseId: "4", and thecoursesarray has any element withoutcourseProgress"
These don't have to be the same element! The positional $ operator then picks the first array element that matches any of the array conditions—so in your sample document, it's updating the courseId: "4" element (which has courseProgress: 100), which violates your requirements.
The Corrected Query
To fix this, use $elemMatch to group both courseId and courseProgress conditions together, ensuring they apply to the same array element:
db.table.update( { enterpriseId: 13, completionStatus: { $ne: "F" }, courses: { $elemMatch: { courseId: "4", courseProgress: { $exists: false } } } }, { $set: { "courses.$.courseId": "45", "courses.$.courseName": "testCourse" } }, { multi: true } )
How This Works
- The
$elemMatchclause ensures we only match documents where one single element in thecoursesarray meets both criteria:courseId: "4"and nocourseProgressfield exists. - The positional
$operator now correctly targets that specific matching element, so only the element you want is updated. - Your sample document won't be matched at all (since its
courseId: "4"element hascourseProgress: 100), which aligns perfectly with your needs.
内容的提问来源于stack exchange,提问作者Abhishek Kumar

