Home > Enterprise >  mongodb - How to increment a field conditionally based on value of another field in same collection?
mongodb - How to increment a field conditionally based on value of another field in same collection?

Time:01-11

How to modify the query below to increment conditionally

  • by 1 if published: false
  • by a_Variable if published: true

where published is another field in the same collection posts

  await db.collection('posts').updateOne(
    {_id: postId},
    {$inc: {rep: a_Variable } //increment by 1 if published: false
  });

CodePudding user response:

db.collection.updateOne({
  "_id": postId
},
[
  {
    $set: {
      rep: {
        $cond: {
          if: {
            $eq: ["$published",false]
          },
          then: {
            $add: ["$rep",1]
          },
          else: {
            $add: ["$rep",a_Variable]
          }
        }
      }
    }
  }
])

Demo

CodePudding user response:

db.collection('posts').updateOne(
{ _id: postId},
[
 { $inc: { rep: { $switch: {
    branches: [
    { case: { $eq: [ "$published", false ] }, then: 1 },
    { case: { $eq: [ "$published", true ] }, then: a_Variable }
    ],
    default: ""
    } } } }
 ])
  • Related