Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a substring in a field in Mongodb

Tags:

mongodb

nosql

How can I find all the objects in a database with where a field of a object contains a substring?

If the field is A in an object of a collection with a string value:

I want to find all the objects in the db "database" where A contains a substring say "abc def".

I tried:

db.database.find({A: {$regex: '/^*(abc def)*$/''}}) 

but didn't work

UPDATE

A real string (in unicode):

Sujet  Commentaire sur  Star Wars  Episode III - La Revanche des Sith 1 

Need to search for all entries with Star Wars

db.test.find({A: {$regex: '^*(star wars)*$''}}) not wokring 
like image 472
codious Avatar asked Apr 20 '12 08:04

codious


2 Answers

Instead of this:

db.database.find({A: {$regex: '/^*(abc def)*$/''}}) 

You should do this:

db.database.find({A: /abc def/i }) 

^* is not actually valid syntax as ^ and $ are anchors and not something that is repeatable. You probably meant ^.* here. But there is no need for ^.* as that simply means "Everything up to the character following" and (abc def)* means "0 or more times "abc def", but it has to be at the end of the string, because of your $. The "i" at the end is to make it case insensitive.

like image 171
Derick Avatar answered Sep 29 '22 05:09

Derick


Just use the string "Star Wars" and $regex will do the rest

db.test.find({A: {$regex: 'Star Wars'}}) 
like image 27
LuisCarlos Rodriguez Avatar answered Sep 29 '22 05:09

LuisCarlos Rodriguez