pymongo處理正則表達式的情況


在python里使用pymongo處理mongodb數據庫,在插入或者查詢的時候,我們有時需要使用操作符號,如set,in,

具體操作符的可以參考  https://docs.mongodb.com/manual/reference/operator/query/

需求:需要用到正則表達式 來插入 或查詢,如何操作?

1.首先要了解一下,mongodb里面的正則表達式怎么用

參考:https://docs.mongodb.com/manual/reference/operator/query/regex/

使用如下語法:

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

或者

{ <field>: /pattern/<options> }

當然option的含義是對正則表達式的一種選擇,有

i  不區分大小寫

m  包含錨的模式(即起始為 ^,結束為 $)

x   擴展

s   允許.點字符

詳細的參考官網,這只是很簡單的介紹

2.在pymongo里如何使用

mongodb默認使用的是bson數據,所以要在python里轉換為該格式的數據

import bson

然后參照官網教程:http://api.mongodb.com/python/current/api/bson/regex.html

>>> pattern = re.compile('.*')
>>> regex = Regex.from_native(pattern)
>>> regex.flags ^= re.UNICODE
>>> db.collection.insert({'pattern': regex})

這里注意一下,Regex是bson的類,可以導入

我的實例: 

    for collection in col_list:
        pattern = re.compile(time.strftime('%Y-%m-%d'))
        regex = bson.regex.Regex.from_native(pattern)
        regex.flags ^= re.UNICODE
        for item in db[collection].find({"insert_time":regex}):
            for j in item['value']:
                ...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM