Open kagxin opened 5 years ago
from pymongo import MongoClient
mongo_uri = 'mongodb://root:root@localhost:27017'
connection = MongoClient(mongo_uri)
m = connection['demo']
where
查询中的where例子this
是指当前这条document,`this.a指文档中的a字段where
对应的function中return为ture的条目会被查询出来where
无法使用索引from mongo import m
import pymongo
m.get_collection('test').create_index([('a', pymongo.DESCENDING), ])
func = """
function() {
if (this.a > 1) {
return true;
}
}
"""
cur = m.get_collection('test').find(
{
'a': {'$gte': 1},
'$where': func
}
)
print(list(cur))
”“”
集合中的内容:
{
"_id" : ObjectId("5dd235baa9acfb97467a85c5"),
"a" : 1
}
{
"_id" : ObjectId("5dd235d01bb622b0c987d268"),
"a" : 1
}
{
"_id" : ObjectId("5dd2432a1d8e957984fdbad7"),
"a" : 2
}
查询结果:
[{'_id': ObjectId('5dd2432a1d8e957984fdbad7'), 'a': 2}]
“”“
.skip(page_size*(page-1)).limit(page_size)
skip
略过大量的数据条目时,性能较差skip
前n页,引导用户使用时间
等其他索引过滤条件,减小数据集范围。db.setProfilingLevel(1, 500) ## 大于500ms,不指定阈值时默认是100ms。
db.setProfilingLevel(2) ## 记录所有日志日志
查询日志会在system.profile这个集合里。
stats 的第一个参数是scalar是数据缩放比例,要查看以MB为单位的数据 stats(1024*1024),以KB为单位 stats(1024)
db.getCollection('users').stats(1024*1024) ## 集合users的大小,以MB为单位 Object.bsonsize(db.getCollection('users').findOne({})) ## 指定document的大小 db.stats() # 数据库的大小
db.getCollection().stats字段的解释
key | 解释 |
---|---|
size | 未压缩时集合的大小,不包括索引 |
count | 集合中document的数量 |
avgObjsize | 平均每个document的大小 |
storageSize | 压缩后集合的大小,不包括索引 |
totalIndexSize | 所有索引的大小 |
indexSizes | 各个索引的大小 |
scaleFactor | 缩放比例 |
ref: https://docs.mongodb.com/manual/reference/method/db.collection.stats/index.html
https://docs.mongodb.com/manual/reference/command/collStats/#collstats-output
查询出集合中,文档中的数组中的元素都满足特定条件的文档