Home > OS >  How to remove the array elements from an array only if the string has a substring named abc.com in M
How to remove the array elements from an array only if the string has a substring named abc.com in M

Time:11-14

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]']
}

CodePudding user response:

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

CodePudding user response:

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()
    })
})
  • Related