John
John

Reputation: 2761

Update if there is no such element

I have a document

{
 videoSection:{
   title: "Social construction",
   videos: [
    {title: "a", isApproved: true},
    {title: "b", isApproved: false},
    {title: "c", isApproved: true},
   ],
   isPublished: false
 }

}

I need to update the document (to set isPublished: true) if all the isApproved fields of the videos of videoSection is true which means if there is no isApproved = false.

What is the way of doing this ?

Upvotes: 2

Views: 33

Answers (2)

Demo - https://mongoplayground.net/p/obReFQ3FmkV

db.collection.update(
{
   "videoSection.videos.isApproved": {
     $exists: true,
     $ne: false
   }
},
{ $set: { "videoSection.isPublished": true } },
{ multi: true }
)

Note - { $exists: true } this add extra checks for the case where videos array is empty or not present, update will not happen.

Upvotes: 2

turivishal
turivishal

Reputation: 36154

  • check condition if isApproved is not false then update isPublished to true
db.collection.updateMany({
  "videoSection.videos.isApproved": {
    $ne: false
  }
},
{
  $set: {
    "videoSection.isPublished": true
  }
})

Playground

Upvotes: 1

Related Questions