skip to Main Content

Can someone help me with a query on how to remove strings from an array in mongodb only if the string has a substring "abc.com"

Current result in a collection :

{
 _id: '1',
users: ['[email protected]', '[email protected]', '[email protected]']
}
{
 _id: '2',
users: ['[email protected]', '[email protected]', '[email protected]']
}

Expected Result :

{
     _id: '1',
    users: ['[email protected]']
}
{
     _id: '2',
    users: ['[email protected]', '[email protected]']
}

2

Answers


  1. For a read-only query, you can use the $filter operator to filter the value with doesn’t match the domain address via $not and $regexMatch operator.

    db.collection.aggregate([
      {
        $set: {
          users: {
            $filter: {
              input: "$users",
              cond: {
                $not: {
                  $regexMatch: {
                    input: "$$this",
                    regex: "(?:@abc\.com)$"
                  }
                }
              }
            }
          }
        }
      }
    ])
    

    Demo (Read-only) @ Mongo Playground


    For updating the document(s), you need to use the $pull operator to remove the value from the array if matches the regex.

    db.collection.update({
      users: {
        $regex: "(?:@abc\.com)$"
      }
    },
    {
      $pull: {
        users: {
          $regex: "(?:@abc\.com)$"
        }
      }
    },
    {
      multi: true
    })
    

    Demo (Update) @ Mongo Playground

    Login or Signup to reply.
  2. Maybe this work for you:

    var str="abc.com"
    db.find({users: { $in: [str] }},(err,objects)=>{
    
        if(err)return;
        if(objects.count() ==0) return;
        objects.map(obj=>{
            obj.users = obj.users.filter((name) => !name.includes(str));
            obj.save()
        })
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search