Home > Blockchain >  Can mongo has $cond in $push?
Can mongo has $cond in $push?

Time:11-23

I need to push 1 item to array and save it to mongo if that item is not existed in array.

Sample: I have a record with an array

{
  _id: ObjectId('xxxxx'),
  userEmails: [
    {
      email: '[email protected],
      addedAt: ISODate('xxx')
    }
  ]
}

Current query:

db.users.updateOne(
  { _id: ObjectId('xxxxx') },
  {
    $push: {
      userEmails: {
        email: '[email protected]',
        addedAt: new Date(),
      }
    }
  }
);

I expect if [email protected] is existed, it shouldn't pushed to array. I don't want array have duplicated items

CodePudding user response:

If you want to have a condition in $push, the best way to go will be to go with the $nin operation.

({name: {$nin: ["Shehroz", "virk"]}})

You can replace name with the user Email, so that it verifies the condition before updating

CodePudding user response:

Here We are specifying condition that if [email protected] is not inside userEmail then only we are pushing data.

db.users.updateOne(
{ _id: ObjectId('xxxxx'),"userEmails.email":{$ne: "[email protected]"} },
{
  $push: {
    userEmails: {
      email: '[email protected]',
      addedAt: new Date(),
    }
  }
});
  • Related