collection users 原始数据
{
"_id" : 1.0,
"name" : "sue",
"age" : 19.0,
"type" : 1.0,
"status" : "P",
"favorites" : {
"artist" : "Picasso",
"food" : "pizza"
},
"finished" : [
17.0,
3.0
],
"badges" : [
"blue",
"black"
],
"points" : [
{
"points" : 85.0,
"bonus" : 20.0
},
{
"points" : 85.0,
"bonus" : 10.0
}
],
"scholarship" : "First-class",
"scholar" : 20000.0,
"address" : {
"province" : "hunan",
"city" : "cs"
}
}
{
"_id" : 3.0,
"name" : "ahn",
"age" : 22.0,
"type" : 2.0,
"status" : "A",
"favorites" : {
"artist" : "Cassatt",
"food" : "cake"
},
"finished" : [
6.0
],
"badges" : [
"blue",
"red"
],
"points" : [
{
"points" : 81.0,
"bonus" : 8.0
},
{
"points" : 55.0,
"bonus" : 20.0
}
],
"scholarship" : "from-david",
"scholar" : 20000.0,
"address" : {
"province" : "hunan",
"city" : "cs"
}
}
{
"_id" : 4.0,
"name" : "xi",
"age" : 34.0,
"type" : 2.0,
"status" : "D",
"favorites" : {
"artist" : "Chagall",
"food" : "chocolate"
},
"finished" : [
5.0,
11.0
],
"badges" : [
"red",
"black"
],
"points" : [
{
"points" : 53.0,
"bonus" : 15.0
},
{
"points" : 51.0,
"bonus" : 15.0
}
],
"scholarship" : "from-chalie",
"scholar" : 20000.0,
"address" : {
"province" : "hunan",
"city" : "cs"
}
}
{
"_id" : 5.0,
"name" : "xyz",
"age" : 23.0,
"type" : 2.0,
"status" : "D",
"favorites" : {
"artist" : "Noguchi",
"food" : "nougat"
},
"finished" : [
14.0,
6.0
],
"badges" : [
"orange"
],
"points" : [
{
"points" : 71.0,
"bonus" : 20.0
}
],
"scholarship" : "from-min",
"scholar" : 99999.0,
"address" : {
"province" : "hunan",
"city" : "cs"
}
}
{
"_id" : 6.0,
"name" : "abc",
"age" : 43.0,
"type" : 1.0,
"status" : "A",
"favorites" : {
"food" : "pizza",
"artist" : "Picasso"
},
"finished" : [
18.0,
12.0
],
"badges" : [
"black",
"blue"
],
"points" : [
{
"points" : 78.0,
"bonus" : 8.0
},
{
"points" : 57.0,
"bonus" : 7.0
}
],
"scholarship" : "from-kkdk",
"scholar" : 12000.0,
"address" : {
"province" : "hunan",
"city" : "cs"
}
}
def find():
d = mongo_db['users'].find(
# filter 是查询的过滤器,结果会符合filter的查询条件
filter={
# 'name': 'David li', # 全匹配
'address.province': 'hunan', # 内层结构全匹配
'address.city': {'$in': ['cs', 'yy']}, # 城市必须是cs, yy的
'scholarship': {'$exists': True}, # 是否存在
'scholar': {'$gt': 14000, '$lt': 80000},
'$or': [{'name': {'$regex': 'ah.*'}}, {'name': 'sue'}],
},
# projection是对列的过滤,结果只包括存在的列
projection={
'name': 1,
'address.city': 1,
'scholar': 1,
'_id': 0
},
skip=0, # 成第0个找到的项开始
limit=20, # 获取20个数据
# sort={'scholar': 1}
)
'''
其他比较符 nin, eq, ne, lt, lte, gte,
'''
d.sort('name', -1) # -1代表倒序,1升序;因为Python的语法习惯,会与mongodb的脚本有一定区别,再阅读文档时要注意
for a in d:
print(a)
输出:
{'address': {'city': 'cs'}, 'scholar': 20000.0, 'name': 'sue'}
{'address': {'city': 'cs'}, 'scholar': 20000.0, 'name': 'ahn'}