skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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(),
        }
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search