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 ?
Can I remove documents of mongodb using regex expression?
Asked Answered
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.
Thank~ I just wonder why it does not support such a operation. –
Anthocyanin
@Anthocyanin What do you mean "does not support"? Any "query" is allowed, this and the full BSON form of
$regex
are valid queries. –
Carhart to remove documents using regex expression –
Anthocyanin
@Anthocyanin That is what the statement above does. It removes matching a regular expression. If that is not clear then your question is not clear. Either try it or explain what you mean by editing your question –
Carhart
Now I know it can remove documents using regex expression. Perhaps 'I just wonder why it does not support such a operation' makes unclear statements because of my poor English. –
Anthocyanin
@Anthocyanin Language does appear to be the problem here. The statement works. If you expect something different then you need to find out how to explain yourself, change your question and then notify when you have made yourself clearer. You are currently not explaining what else you could possibly mean. –
Carhart
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
I have used deleteMany method:
db.collection.deleteMany({ "field": /^string/ })
© 2022 - 2024 — McMap. All rights reserved.