2

So, I've decided to get my feet wet with MongoDB and love it so far. It seems very fast and flexible which is great. But, I'm still going through the initial learning curve and as such, I'm spending hours digging for info on the most basic things.

I've search throughout the MongoDB online documentation and have spent hours Googling through pages without any mention of this. I know Mongo is still quite new (v1.x) so it explains why there isn't much information yet. I've even trying looking for books on Mongo without much luck. So yes, I've tried to RTM with no luck, so, now I turn to you.

I have an Array of various Hashtags nested in each document (ie: #apples, #oranges, #Apples, #APPLES) and I would like to perform a case-insensitive find() to access all the documents containing apples in any case. It seems that find does support some regex with /i, but I can't seem to get this working either.

Anyway, I hope this is a quick answer for someone.

Here's my existing call in PHP which is case sensitive:

$cursor = $collection->find(array( "hashtags" => array("#".$keyword)))->sort(array('$natural' => -1))->limit(10);

Help?

Community
  • 1
  • 1
Hal
  • 1,173
  • 12
  • 11

2 Answers2

0

here is an example for case insensitive search in mongodb with php

$search_string='baR';

$searchQuery = array(
            '$or' => array(
                array(
                    'field1' => new MongoRegex("/^$search_string/i"),
                    ),
                array(
                    'field2' => new MongoRegex("/^$search_string/i"),
                    ),
                )
            );

$cursor = $customers->find($searchQuery);

Hopes this help any.

Thusitha Sumanadasa
  • 1,669
  • 2
  • 22
  • 30
  • 1
    I think you mean: `new MongoRegex("/^search_string$/i")`, don't you? – aymericbeaumet Apr 01 '15 at 14:04
  • `MongoRegex` has been deprecated for `MongoDB\BSON\Regex`, so now you'd do `new MongoDB\BSON\Regex("^$search_string\$", "/i")` for a case-insensitive lookup for the variable `$search_string`. – MikeOShay Mar 03 '21 at 22:01
0

I suspect your query is not returning what you really want...

If you do

db.col.find( { some_array_field: ["item1", "item2"] } );

then it will only match documents that have EXACTLY these two items in some_array_field. So if there is a document with [item1, item2] hashtags it will match, but a document with [item1, item2, item3] tags won't match.

You could use the $all argument as described in this post:

How do you do an AND query on an array in mongodb?

e.g.

db.col.find( { some_array_field: { $all : ["item1", "item2"] } } );

or:

db.col.find( { some_array_field: "item1", some_array_field: "item2" } );

This distinction of complete-document-match and partial-match was really confusing in MongoDB for me at first.

Community
  • 1
  • 1
Jakub P.
  • 5,416
  • 2
  • 21
  • 21