批量插入以及性能测试
性能优化的思想应当由始至终的贯穿于我们的应用程序之中
批量插入
- 新建文件
mongodb-2.js
- 输入以下代码
var db = connect('performance')
const arr = [
{ id1: 1 },
{ id2: 2 },
{ id3: 3 },
{ id4: 4 },
]
db.arr.insert(arr)
print('arr.length:' + arr.length);
- 执行命令看cmd输出
D:\Code\Test\Others>mongo mongodb-2.js
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
connecting to: mongodb://127.0.0.1:27017/performance
MongoDB server version: 3.4.4
arr.length:4
- 验证数据是否入库
> use performance
switched to db performance
> show collections
arr
> db.arr.find()
{ "_id" : ObjectId("5ef21a4288f0ed6ebf7c2427"), "id1" : 1 }
{ "_id" : ObjectId("5ef21a4288f0ed6ebf7c2428"), "id2" : 2 }
{ "_id" : ObjectId("5ef21a4288f0ed6ebf7c2429"), "id3" : 3 }
{ "_id" : ObjectId("5ef21a4288f0ed6ebf7c242a"), "id4" : 4 }
性能测试
- 循环插入数据
- 新建文件
mongodb-3.js
,并输入以下代码
var db = connect('performance')
var startTime = (new Date()).getTime(); //得到开始时间
for (let q = 0; q < 1000; q++) {
db.arr2.insert({
id: q
})
}
var runTime = (new Date()).getTime() - startTime;//计算时间差
print('This run this is:' + runTime + 'ms');//打印出来
- 执行命令看输出时间
D:\Code\Test\Others>mongo mongodb-3.js
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
connecting to: mongodb://127.0.0.1:27017/performance
MongoDB server version: 3.4.4
This run this is:262ms
用了 262ms
- 一次性插入数据
- 新建文件
mongodb-4.js
,并输入以下代码
var db = connect('performance')
var startTime = (new Date()).getTime(); //得到开始时间
const arr = []
for (let q = 0; q < 1000; q++) {
arr.push({
id: q
})
}
db.arr3.insert(arr)
var runTime = (new Date()).getTime() - startTime;//计算时间差
print('This run this is:' + runTime + 'ms');//打印出来
- 执行命令看输出时间
D:\Code\Test\Others>mongo mongodb-4.js
MongoDB shell version v3.4.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
connecting to: mongodb://127.0.0.1:27017/performance
MongoDB server version: 3.4.4
This run this is:17ms
只用了 17ms
由此可见一次性插入批量数据的性能要远远优于循环插入批量数据的性能
网友评论