码迷,mamicode.com
首页 > 其他好文 > 详细

pymongo处理正则表达式的情况

时间:2017-12-11 18:42:18      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:正则   正则表达   field   current   man   mon   nic   pil   https   

在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]:
                ...

 

pymongo处理正则表达式的情况

标签:正则   正则表达   field   current   man   mon   nic   pil   https   

原文地址:http://www.cnblogs.com/dahu-daqing/p/8023775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!