开发者

Perform case-insensitive lookup on an Array in MongoDB?

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜