1. 数组是数字、字符串
假设mongo的test集合中有如下的文档,
# documents
{'_id':xxx, 'name': '张三', 'visit_url': ['http://www.baidu.com', 'http://www.qq.com'], 'date': ISODate('2019-09-04 00:00:00')},
{'_id':xxx, 'name': '李四', 'visit_url': ['http://www.aliyun.com', 'http://www.qq.com'], 'date': ISODate('2019-09-04 12:00:00')},
在python脚本中使用pymongo执行mongo语句
import pymongo
client = pymongo.MongoClient('mongodb://your_user:your_password@host:port/') # 建立连接
db = client.my_db # 你的数据库
filter_find = {'visit_url': {'$in': ['http://www.baidu.com']}}
# 在mongo中使用如下语句查询
result_set = list(db.test.find({filter_find}))
print(result_push)
2. 数组中是一个个对象
假设mongo的test集合中有如下的文档,
# documents
{'_id':xxx, 'name': '张三', 'visit_url': [{'proto', 'http', 'host': 'www.baidu.com'}, {'proto': 'https', 'host':'www.qq.com'}], 'date': ISODate('2019-09-04 00:00:00')},
{'_id':xxx, 'name': '李四', 'visit_url': [{'proto', 'https', 'host': 'aliyun.com'}, {'proto': 'https', 'host':'www.baidu.com'}, 'date': ISODate('2019-09-04 12:00:00')},
在python脚本中使用pymongo执行mongo语句
import pymongo
client = pymongo.MongoClient('mongodb://your_user:your_password@host:port/') # 建立连接
db = client.my_db # 你的数据库
filter_find = {'visit_url': {'$elemMatch': {'proto': 'https', 'host': 'www.baidu.com'}}}
# 在mongo中使用如下语句查询
result_set = list(db.test.find({filter_find}))
print(result_push)
若是按照数组中元素的某字段排序
db.getCollection('test').aggregate([
//{'$match': {'codes.name': 'a'}}, // 检索文档
{'$unwind': "$codes"}, // 拆分哪个数组数组
//{'$match': {'codes.name': 'a'}}, // 检索数组元素
{'$sort': {'codes._id': -1}},
{'$skip': 2},
{'$limit': 3}
])
总结
主要是看需要查询的该数组的具体结构,如果数组中直接就是存放的值,那么就用第一中方法( i n in in),如果数组中存放的是一个个字典,那么用第二种方法( e l e m M a t c h elemMatch elemMatch)。
参考文献
[1] 如何查询MongoDB中,一个数组是否包含指定的数据
[2] mongodb对数组中的元素进行查询详解
[2] mongo 数组元素检索与排序