mongodb 查询优化 主要针对count慢


数据 1800万 数据一直增加中

优化前 耗时:7.9s(未加索引,查询时CPU飞了)

filter = bson.D{{"userid", userid}, {"height", height}}
Txs, err := c.Mgo.Collection(m.UserTxs).Find(context.Background(), filter, opts)
sCount, err := c.Mgo.Collection(m.UserTxs).CountDocuments(context.Background(), filter)

优化后 耗时: 8-15ms (这里毫秒)    添加索引(这里添加对当前条件索引)
索引

{
    "height" : 1,
    "userid" : 1
}


sCount, err := c.Mgo.Collection(m.UserTxs).CountDocuments(context.Background(), filter)

//这里使用CountDocuments 函数时可根据查询条件  指定强制使用某个索引

optCount := new(options.CountOptions)
optCount.Hint =“_id_”  //“—id_” 这里是索引的名字
sCount, err := c.Mgo.Collection(m.BlockTxs).CountDocuments(context.Background(), filter, optCount)


总数优化使用  CountDocuments 速度无明显提升
        后使用: EstimatedDocumentCount
优化后速度提升显著 到毫秒级 

func getEstimatedDocumentCount(c *Chain ,tableName string ) int64 {
    count,_:=c.Mgo.Collection(tableName).EstimatedDocumentCount(context.Background(),options.EstimatedDocumentCount().SetMaxTime(9000000000000))
    return  count
}

发布了123 篇原创文章 · 获赞 47 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/u010919083/article/details/94859638