-2

I am trying to pull out the results from mongoDB using mongoose ORM. The below code part worked perfectly and returned the exact matches of 'Test'

db.getCollection('cards').find({
    $where: "this.name=='Test'"
})

I actually wanted to pull out the case-insensitive matches of 'Test'.

Below one worked,

db.getCollection('cards').find({"name":/test/i})

But I wanted to use regex on $where as below,

db.getCollection('cards').find({
    $where: "this.name=='/Test/i'"
})

can someone throw some light or direction on how to address regex within $where?

Cling
  • 489
  • 1
  • 6
  • 15
  • @npinti this is not a duplicate as my requirement is to use $where keyword – Cling Jul 31 '15 at 07:09
  • @Cling: I wasn't sure, so I did not vote to close. Thanks for the correction. comment removed. – npinti Jul 31 '15 at 07:10
  • @Cling You might be "using" `$where` but you probably should not be unless you need more JavaScript based logic in there than what you are doing. JavaScript evalution can "only" scan the entire collection. A proper "$regex" query can at least just scan the entire index. And even less of the index if you include a caret `^` – Blakes Seven Jul 31 '15 at 07:15
  • Dupicate of http://stackoverflow.com/questions/7101703/how-do-i-make-case-insensitive-queries-on-mongodb – Blakes Seven Jul 31 '15 at 07:22
  • whats the reason for downvotes?? – Cling Jul 31 '15 at 08:51

1 Answers1

2
db.getCollection('cards').find({"name": /Test/i})

the above query will give you any name containing "test" in it

if you want to do a search with using $where

use this:

db.getCollection('cards').find({ $where: "/Test/.test(this.name)" })

IMHO you can use $regex itself.

{ <field>: { $regex: /pattern/, $options: '<options>' } }

example:

db.getCollection('cards').find({ name: { $regex: /Test/, $options: 'i' } })
aelor
  • 10,892
  • 3
  • 32
  • 48