Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I remove documents of mongodb using regex expression?

I have not find a method to do it yet. If we can not remove documents using regex expression, what can we do to make it done? And why does not mongodb provide such a driver ?

like image 315
Canoe Avatar asked Jul 17 '14 07:07

Canoe


People also ask

Can we use regex in MongoDB?

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax. The following <options> are available for use with regular expression.

How do I remove all files from a collection in MongoDB?

To delete all documents in a collection, pass an empty document ( {} ). Optional. To limit the deletion to just one document, set to true . Omit to use the default value of false and delete all documents matching the deletion criteria.

How do you remove something from a document in MongoDB?

In MongoDB, you can use the $unset field update operator to completely remove a field from a document. The $unset operator is designed specifically to delete a field and its value from the document.


2 Answers

The .remove() method just takes a query object, so regular expressions are just a standard query for MongoDB:

db.collection.remove({ "field": /^string/ })

Removes anything that has "field" that starts with "string"

Look at the documentation for $regex as well.

like image 194
Neil Lunn Avatar answered Oct 18 '22 21:10

Neil Lunn


Documents can be remove using remove() method and $regex query.

For example

db.users.remove({"email" :  { $regex : /$test/}})

It will remove all user email starts with 'test'.

db.users.remove({"email" :  { $regex : /@yopmail.com$/}})

It will remove all user email ends with 'yopmail.com'

Details are explained here, mongoDB official site

like image 1
Jakarea Parvez Avatar answered Oct 18 '22 21:10

Jakarea Parvez