Ishimura_Hideo
Ishimura_Hideo

Reputation: 43

MongoDB: update document field with a condition

I have an object which looks like this:

const prod = {
    _id: 123123123,
    name: "car",
    description: "BMW X6"
}

I use Mongoose to work with Mongo. I need to find a document with the exactly same _id and then take a look at its 'description' field. If it has null (or any other falsy value) I need to update document, using 'description' from the object above. If a document already has description, this field remains the same (no update).

How do I do this?

Upvotes: 1

Views: 2566

Answers (1)

mohammad Naimi
mohammad Naimi

Reputation: 2359

use pipleline in update like this

db.collection.update({_id:123123123},
[
  {
    $set: {
      description: {
        $cond: {
          if: {
            $or: [
              {
                $eq: [
                  false,
                  "$description"
                ]
              },
              {
                $eq: [
                  null,
                  "$description"
                ]
              },
              {
                $eq: [
                  "",
                  "$description"
                ]
              }
            ]
            
          },
          then: 1,
          // overwrite prop value
          else: "$description",
          // return origin value
          
        }
      }
    }
  }
])

https://mongoplayground.net/p/GHJIYFXhM4V

Upvotes: 1

Related Questions