1
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.

I have made this query but still updated the document even courseProgress is exists on second index of array

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}
)

Still this query is updated the field even though courseProgress is exists on array's second index.As i am new to mongodb,Please help me on this issue.

1 Answer 1

1

$ only updates the first element it matches in the array. To update all the matched elements of the array you need to use $[].

Try this :

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}
)

For detailed information, please read $[] Mongo documentation

Sign up to request clarification or add additional context in comments.

2 Comments

I am using mongodb 3.4 ,$[] is available in version 3.6
If you dont have version 3.6 or higher, you need to do a find(), update the array manually and save it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.