20

I run following query in mongo shell:

db.Profiles.find ( { $or : [ { "name" : "gary" }, {"name":"rob} ] } )

It just returns nothing as expected(JSON)?

AD7six
  • 63,116
  • 12
  • 91
  • 123
Fruitful
  • 597
  • 2
  • 9
  • 16
  • I have reverted that edit, it is not helpful to edit one of the OPs original problems out of the question. – AD7six May 21 '20 at 11:48

1 Answers1

48

Use $in

For the query in the question, it's more appropriate to use $in

db.Profiles.find ( { "name" : { $in: ["gary", "rob"] } } );

Why doesn't it work

There's a missing quote - the cli is waiting for you to finish the second part of your or:

db.Profiles.find ( { $or : [ { "name" : "gary" }, {"name":"rob} ] } )
..............................................................^

You need to finish the query sufficiently for the cli to parse it for it to then say there's a syntax error.

Case insensitive matching

As indicated by a comment, if you want to search in a case insensitive manner, then you either use $or with a $regex:

db.Profiles.find ( { $or : [ { "name" : /^gary/i }, {"name": /^rob/i } ] } )

Or, you simply use one regex:

db.Profiles.find ( { "name" : /^(gary|rob)/i } )

However, a regex query that doesn't start with a fixed string cannot use an index (it cannot use an index and effectively do "start here until no match found then bail") and therefore is sub-optimal. If this is your requirement, it's a better idea to store a normalized name field (e.g. name_lc - lower case name) and query on that:

db.Profiles.find ( { "name_lc" : { $in: ["gary", "rob"] } } );
AD7six
  • 63,116
  • 12
  • 91
  • 123
  • Wow, bad mistake. Thanks @AD7six – Fruitful Jan 26 '13 at 07:57
  • Your suggested query works much better. Do I need to change any syntax if say names were capitalised in an array? e.g. name:["Gary", "rob"] – Fruitful Jan 26 '13 at 08:02
  • db.Profiles.find ( { "names" : { $in: [/gary/i, /rob/i] } } ) answered my own question I think. – Fruitful Jan 26 '13 at 08:08
  • 1
    @Fruitful will work - be wary of relying on queries that cannot be indexed - use [ensureIndex](http://docs.mongodb.org/manual/reference/method/db.collection.ensureIndex/#db.collection.ensureIndex) appropriately and [profile](http://docs.mongodb.org/manual/reference/command/profile/) the db to identify slow queries (or use [explain](http://docs.mongodb.org/manual/reference/method/cursor.explain/) on individual queries). Otherwise with time things just get slow or stop being viable. – AD7six Jan 26 '13 at 08:13