$or not working with multiple $regex (partial text match across multiple fields)

213 views
Skip to first unread message

Raymond Barlow

unread,
Nov 3, 2011, 6:58:36 AM11/3/11
to mongod...@googlegroups.com
Hi all,

Given a collection users, with:

{ "firstName" : "raymond", "lastName" : "Barlow" }

This works as expected (found):
> db.users.find({"firstName":{$regex:".*ray.*"}})
{ "firstName" : "raymond", "lastName" : "Barlow" }

As does this (not found):
> db.users.find({"lastName":{$regex:".*ray.*"}})
>

But, this does not work as I would have expected:
> db.users.find({$or:[{"firstName":{$regex:".*ray.*"}},{"lastName":{$regex:".*ray.*"}}]})
>

Certainly, it should have matched the email regex?

Basically, I'm trying to implement a search function that works over a number of fields. On the front end, the user searches for any partial string, and it gets matched to a number of different fields in the user object. Is there a better way to achieve this?

I am using version 2.0.1.

Help/advice appreciated!

Regards,
Raymond Barlow

Nat

unread,
Nov 3, 2011, 7:50:54 AM11/3/11
to mongod...@googlegroups.com
Which version do you use? Can you attach your explain() plan for that one?
From: Raymond Barlow <mrraymo...@gmail.com>
Date: Thu, 3 Nov 2011 03:58:36 -0700 (PDT)
Subject: [mongodb-user] $or not working with multiple $regex (partial text match across multiple fields)
--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To view this discussion on the web visit https://groups.google.com/d/msg/mongodb-user/-/R9VX1Nka8IIJ.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.

Marc

unread,
Nov 3, 2011, 1:06:30 PM11/3/11
to mongodb-user
Interesting. I cannot seem to reproduce this on my system. Are you
sure that the $or query was typed in correctly?

> db.version()
2.0.1
> version()
version: 2.0.1
> db.users.save({_id:1, "firstName" : "raymond", "lastName" : "Barlow" } )
> db.users.find()
{ "_id" : 1, "firstName" : "raymond", "lastName" : "Barlow" }
> db.users.find({$or:[{"firstName":{$regex:".*ray.*"}},{"lastName":{$regex:". *ray.*"}}]})
{ "_id" : 1, "firstName" : "raymond", "lastName" : "Barlow" }
>

Can you give the exact steps that you took to reproduce your issue?
Reply all
Reply to author
Forward
0 new messages