实验前:
func TestInsert(g *gin.Context) {
rsp := new(Rsp)
var tests [] interface{}
for i:=0; i<1000000 ;i++ {
newuser := new(Test)
newuser.Email =strconv.Itoa(i)
newuser.Username =strconv.Itoa(i)
newuser.Password = strconv.Itoa(i)
newuser.Phone =strconv.Itoa(i)
newuser.Address = strconv.Itoa(i)
newuser.CreateTime= int32(time.Now().Unix())
newuser.Height= int32(i)
tests=append(tests,newuser)
}
mgo := db.InitMongoDB()
insertID, err := mgo.Collection(db.Test).InsertMany(context.Background(), tests,nil)
fmt.Println(insertID)
if err == nil {
rsp.Msg = "success"
rsp.Code = 200
g.JSON(http.StatusOK, rsp)
return
} else {
rsp.Msg = "faild"
rsp.Code = 201
g.JSON(http.StatusOK, rsp)
return
}
}
db.getCollection('test').find({"height":500000})
需要时间 0.685sec
优化
添加索引:db.test.createIndex( {“height”:1})
查询:
db.getCollection('test').find({"height":500000})
需要时间 0.003sec
{
"_id" : ObjectId("5cdbb0c60839769587c2b90c"),
"username" : "500000",
"password" : "500000",
"address" : "500000",
"gender" : 0,
"email" : "500000",
"phone" : "500000",
"createtime" : 1557901500,
"height" : 500000
}