Reputation: 858
I'm creating a search page for my application and its using MongoDB. So I need to search an array of strings in multiple fields.
When I search in a single field, I do this:
$docs = $collection->find(array('username' => new MongoRegex("/^query/"));
But when I search for multiple fields, what do I need to do? Something like this?
$docs = $collection->find(array('username','name', 'email' => new MongoRegex("/^query/"));
Upvotes: 1
Views: 1817
Reputation: 42352
Here is a page that documents how to query MongoDB from PHP: http://php.net/manual/en/mongocollection.find.php
You may be thinking that because you want to compare multiple fields to the same value that there would be a special (shorter) syntax for it (just like when you want to compare a single field to multiple values, like in a range query).
However, that is not the case - you still have to list every field and that value you are comparing it to, as if each field was being compared to a different value.
The only other thing to consider is whether you are searching for all documents that have any of the fields match this regex or all of the fields match the regex. In the first case you have to do an "$or" query. See the last example on the bottom of the manual page for syntax.
Upvotes: 3