最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Mongo中让搜索支持不区分大小写

MongoDB crifan 2776浏览 0评论

一个系统中,搜索儿歌名字,输入大小写一致的名字,是可以搜索到的:

-》

但是大小写错了后,就搜不到了:

希望支持不区分大小写

查看了内部代码是:

<code>
class MongoDBGridFsFiles(APIView):
    permission_classes = (AllowAny, )

    def get(self, request):
        """
            获取 mongodb gridfs 文件列表,带翻页,search可不传
            /api/v1/mongodb_gridfs_files/?page=1&amp;page_size=20&amp;search=
        """
        ...
        api_url_partial = '/api/v1/mongodb_gridfs_files/?page='
        if request.is_secure:
            protocal = 'https'
        else:
            protocal = 'http'
        api_url = protocal + current_host + api_url_partial
        search = request.query_params.get('search', '')
        page = request.query_params.get('page', 1)
        page_size = request.query_params.get('page_size', 20)
        if search:
            file_list = [[str(i._id), i.filename] for i in grid_fs_collection.find({'metadata.fileInfo.isAudio': True, "filename": {"$regex": search}})]
        else:
            file_list = [[str(i._id), i.filename] for i in grid_fs_collection.find({'metadata.fileInfo.isAudio': True})]
        p = Paginator(file_list, page_size)
</code>

很明显,此处的搜索,是通过mongo中传递

“filename”: {“$regex”: search}

去实现搜索结果的。

此处需要去搞清楚,如何支持大小写。

db.collection.find() — MongoDB Manual

Operators — MongoDB Manual

Query and Projection Operators — MongoDB Manual

mongo find case insensitive

MongoDB: Is it possible to make a case-insensitive query? – Stack Overflow

regex – How do I make case-insensitive queries on Mongodb? – Stack Overflow

Case Insensitive Indexes — MongoDB Manual

MongoDB – Don’t be so (case) sensitive! | (+N) Consulting, Inc.

感觉是:

<code>var thename = 'Andrew';
db.collection.find({'name': {'$regex': thename,$options:'i'}});
</code>

不过还是想要去找的官网的解释

mongo find regex

$regex — MongoDB Manual

https://docs.mongodb.com/manual/reference/operator/query/regex/#syntax-restrictions

支持多种写法:

<code>{ &lt;field&gt;: { $regex: /pattern/, $options: '&lt;options&gt;' } }
{ &lt;field&gt;: { $regex: 'pattern', $options: '&lt;options&gt;' } }
{ &lt;field&gt;: { $regex: /pattern/&lt;options&gt; } }
</code>

【总结】

把代码:

<code>file_list = [[str(i._id), i.filename] for i in grid_fs_collection.find({'metadata.fileInfo.isAudio': True, "filename": {"$regex": search}})]
</code>

改为:

<code>file_list = [[str(i._id), i.filename] for i in grid_fs_collection.find({'metadata.fileInfo.isAudio': True, "filename": {"$regex": search, "$options": "i"}})]
</code>

即可支持 不区分大小写去搜索文件名了:

关于mongo的find中regex和options的解释见官网:

$regex — MongoDB Manual

转载请注明:在路上 » 【已解决】Mongo中让搜索支持不区分大小写

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.159 seconds, using 22.12MB memory