Home > Back-end >  Set document field if only does not exists mongodb
Set document field if only does not exists mongodb

Time:10-19

i have a mongodb document which i want to set a field if does not exists otherwise if the field exists i want to keep it as it is, i don't know what is wrong with my code:

     await UserAnalytics.findOneAndUpdate(
      { user },
      {
        $inc: {
          nbPosts: 1,
        },
      },
      {
        $cond: [
          { bestPost: { $exists: false } },
          { $set: { bestPost: newPost._id } },
          { $set: { bestPost: "$bestPost" } },
        ],
      }
    );

Any help please ?

CodePudding user response:

You have to do it with Aggregation framework. In order to use Aggregation framework in the update query, you need to wrap second input with []:

db.collection.update({
  user: 1
},
[
  {
    "$set": {
      "nbPosts": {
        "$sum": [
          "$nbPosts",
          1
        ]
      },
      "bestPost": {
        "$cond": {
          "if": {
            "$eq": [
              "$bestPost",
              undefined
            ]
          },
          "then": "new_id",
          "else": "$bestPost"
        }
      }
    }
  }
])

Working example

  • Related