kagxin / blog

个人博客:技术、随笔、生活
https://github.com/kagxin/blog/issues
7 stars 0 forks source link

mongodb中的背忘点 #25

Open kagxin opened 5 years ago

kagxin commented 5 years ago

查询出集合中,文档中的数组中的元素都满足特定条件的文档

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

Q: 如何查询出,dic_cm 数组中的所有元素都小于16的记录 即 { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }

A:

db.inventory.find({'dim_cm':{$not:{$gte:16}}})
kagxin commented 4 years ago

公用代码

from pymongo import MongoClient

mongo_uri = 'mongodb://root:root@localhost:27017'
connection = MongoClient(mongo_uri)
m = connection['demo']
kagxin commented 4 years ago

where 查询中的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}]
“”“
kagxin commented 4 years ago

关于分页性能

kagxin commented 4 years ago

关于副本集

kagxin commented 4 years ago

设置记录查询日志

db.setProfilingLevel(1,  500)  ##  大于500ms,不指定阈值时默认是100ms。
db.setProfilingLevel(2) ## 记录所有日志日志

查询日志会在system.profile这个集合里。

kagxin commented 4 years ago

文档集合和db的大小

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