Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Regex Query : Why doesn't this work?

Tags:

regex

mongodb

See second to last input please.

Note: I was using http://try.mongodb.org/

> person = {fullname : "Derek Litz"}
{
     "fullname" : "Derek Litz"
     }
> db.people.save(person)
"ok"
> db.people.find()

    [ 
      {   "_id" : {   "$oid" : "4df3b39ccc93747e68039f08"   },   "fullname" : "Derek Litz"   }
    ]
> db.people.find({fullname : 'Derek Litz'})

    [ 
      {   "_id" : {   "$oid" : "4df3b39ccc93747e68039f08"   },   "fullname" : "Derek Litz"   }
    ]
> db.people.find({fullname : /^D.*/})

    [ 
      
    ]
> db.people.find({fullname : {$regex : '^D.*'}})

    [ 
      {   "_id" : {   "$oid" : "4df3b39ccc93747e68039f08"   },   "fullname" : "Derek Litz"   }
    ]
>
like image 202
Derek Litz Avatar asked Feb 14 '26 02:02

Derek Litz


1 Answers

I think that's just a bug in try.mongodb.org. These work for me in my local mongo shell:

db.people.find({first_name: {$regex: /e/}})
db.people.find({first_name: /e/})

And the documentation says this:

You may use regexes in database query expressions:

db.customers.find( { name : /acme.*corp/i } );
db.customers.find( { name : { $regex : 'acme.*corp', $options: 'i' } } );
[...]
db.customers.find( { name : { $regex : /acme.*corp/i, $nin : ['acmeblahcorp'] } } );

So both string and RegExp literal versions are supported.

like image 139
mu is too short Avatar answered Feb 16 '26 17:02

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!