How to Update selective fields of a document in a collection

Below is how my data is structured in the collection. I want to update only FirstName. When I use $set without sending “images”, it is removing the “images” array and so I am losing it. How do I not disturb other fields but only update the FirstName. Can anyone please advise?

BookId:"BK1234"
UserID:"XX12345"
FirstName: "TestFirstName"
images:Array
    0:Object
    ImgId:"data:image/png;base64,iVBOR..."
UpdatedDate:"2021-09-30"
UpdatedTime:"14:09:41"

If you only $set FirstName it should not remove or update any other fields. Share your code so that we see what is wrong.

Thanks for your response. I tried it that way. but it is completely removing the “images” array.

Before:

BookId:“BK1234”
Ratings: Array
  UserID:“XX12345”
  FirstName: “TestFirstName”
  images:Array
     0:Object
     ImgId:“data:image/png;base64,iVBOR…”
  UpdatedDate:“2021-09-30”
  UpdatedTime:“14:09:41”

Update like below. Note that “images” is commented out.

  var filter = {
    'BookId': arg.bookId,
    'Ratings.UserID': arg.Userid
  };
  

  var ratingUpdate = {
    '$set': {
      'Ratings.$': {
        'UserID': arg.id,
        'FirstName': arg.rating,
        'Rating': arg.rating,
//        'Images': arg.images,        
        'UpdatedDate': arg.CreatedDate,
        'UpdatedTime': arg.CreatedTime

      }
    }
  };
  var bookRatingsDoc = await userBookRatings.updateOne(bookRatingsfilter, ratingUpdate);

After:

BookId:“BK1234”
Ratings: Array
  UserID:“XX12345”
  FirstName: “TestFirstName”
  UpdatedDate:“2021-09-30”
  UpdatedTime:“14:09:41”

It is because you are doing the $set at the Ratings object level. You have to set the fields within. Try:

var ratingUpdate = {
‘$set’: {
‘Ratings.$.UserID’: arg.id,
‘Ratings.$.FirstName’: arg.rating,
‘Ratings.$.Rating’: arg.rating,
// ‘Ratings.$.Images’: arg.images,
‘Ratings.$.UpdatedDate’: arg.CreatedDate,
‘Ratings.$.UpdatedTime’: arg.CreatedTime
} }
1 Like

This is great!! Thanks a lot Steeve for your support and much thanks for the code :slight_smile: I am very new MDB and so this helped me a lot. Thanks again.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.