一个系统中,搜索儿歌名字,输入大小写一致的名字,是可以搜索到的:
-》
但是大小写错了后,就搜不到了:
希望支持不区分大小写
查看了内部代码是:
<code> class MongoDBGridFsFiles(APIView): permission_classes = (AllowAny, ) def get(self, request): """ 获取 mongodb gridfs 文件列表,带翻页,search可不传 /api/v1/mongodb_gridfs_files/?page=1&page_size=20&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
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
https://docs.mongodb.com/manual/reference/operator/query/regex/#syntax-restrictions
支持多种写法:
<code>{ <field>: { $regex: /pattern/, $options: '<options>' } } { <field>: { $regex: 'pattern', $options: '<options>' } } { <field>: { $regex: /pattern/<options> } } </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的解释见官网:
转载请注明:在路上 » 【已解决】Mongo中让搜索支持不区分大小写