国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python操作mongodb數據庫進行模糊查詢操作示例

2020-02-15 21:44:42
字體:
來源:轉載
供稿:網友

本文實例講述了Python操作mongodb數據庫進行模糊查詢操作。分享給大家供大家參考,具體如下:

# -*- coding: utf-8 -*-import pymongoimport refrom pymongo import MongoClient#創建連接#10.20.66.106client = MongoClient('10.20.4.79', 27017)#client = MongoClient('10.20.66.106', 27017)db_name = 'ta'db = client[db_name]

假設mongodb數據庫中school 集合中有一些數據記錄

{ "_id" : 1, "zipcode" : "63109", "students" : { "comments" : "python abc" } }{ "_id" : 2, "zipcode" : "63110", "students" : { "comments" : "python abc" } }{ "_id" : 3, "zipcode" : "63109", "students" : { "comments" : "python abc" } }{ "_id" : 4, "zipcode" : "63109", "students" : { "comments" : "python abc" } }{ "_id" : 5, "zipcode" : "63109", "students" : { "comments" : "python abc" } }{ "_id" : 7, "zipcode" : "63109", "students" : { "comments" : "python abc" }, "school" : "102 python abc" }{ "_id" : 8, "zipcode" : "63109", "students" : { "comments" : "python abc" }, "school" : "100 python abc xyz" }{ "_id" : 9, "zipcode" : "100", "students" : { "name" : "mike", "age" : 12, "comments" : "python" } }{ "_id" : 10, "zipcode" : "100", "students" : { "name" : "Marry", "age" : 42, "comments" : "this is a python" } }{ "_id" : 11, "zipcode" : "100", "students" : { "name" : "joe", "age" : 92, "comments" : "this is a python program" } }{ "_id" : 12, "zipcode" : "100", "students" : { "name" : "joedd", "age" : 34, "comments" : "python is a script language" } }

現在要對students中comments的數據進行模糊查詢, python中模糊查詢要借助正則表達式:

1、查詢comments中包含"abc"的記錄:

for u in db.school.find({'students.comments':re.compile('abc')}):  print u

結果如下:

{u'students': {u'comments': u'python abc'}, u'_id': 1.0, u'zipcode': u'63109'}
{u'students': {u'comments': u'python abc'}, u'_id': 2.0, u'zipcode': u'63110'}
{u'students': {u'comments': u'python abc'}, u'_id': 3.0, u'zipcode': u'63109'}
{u'students': {u'comments': u'python abc'}, u'_id': 4.0, u'zipcode': u'63109'}
{u'students': {u'comments': u'python abc'}, u'_id': 5.0, u'zipcode': u'63109'}
{u'students': {u'comments': u'python abc'}, u'school': u'102 python abc', u'_id': 7.0, u'zipcode': u'63109'}
{u'students': {u'comments': u'python abc'}, u'school': u'100 python abc xyz', u'_id': 8.0, u'zipcode': u'63109'}

2、查詢comments中包含"this is"的記錄:

for u in db.school.find({'students.comments':re.compile('this is')}):  print u

結果如下:

{u'students': {u'age': 42.0, u'name': u'Marry', u'comments': u'this is a python'}, u'_id': 10.0, u'zipcode': u'100'}
{u'students': {u'age': 92.0, u'name': u'joe', u'comments': u'this is a python program'}, u'_id': 11.0, u'zipcode': u'100'}

由此可見,模糊查詢要用到re模塊,查詢條件利用

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 巴林右旗| 胶州市| 泰来县| 铅山县| 宜兴市| 萨迦县| 宁明县| 汶川县| 阳东县| 景东| 伊吾县| 东平县| 基隆市| 屏东县| 洪江市| 铜梁县| 泸溪县| 沿河| 石嘴山市| 双桥区| 屯昌县| 义马市| 东港市| 磴口县| 阳东县| 化州市| 慈利县| 利津县| 边坝县| 武隆县| 疏附县| 寿宁县| 镇赉县| 浙江省| 兴安县| 云梦县| 汝阳县| 嘉荫县| 渑池县| 堆龙德庆县| 石渠县|