1、裝好數據庫
查看庫:show dbs;
創建數據庫:
在 MongoDB 中,集合只有在內容插入后才會創建! 就是說,創建集合(數據表)后要再插入一個文檔(記錄),集合才會真正創建。
新庫需要插入一條內容,否則不保存:db.test.insert({"name":"馬冬梅"})
MongoDB 中默認的數據庫為 test,如果你沒有創建新的數據庫,集合將存放在 test 數據庫中
刪除創建的數據庫,首先使用use切換到要刪除的數據庫,執行刪除命令:
> use test
switched to db test
> db.dropdatabase();
{ "dropped" : "test", "ok" : 1 }
集合刪除語法格式:db.collection.drop()
> use test
switched to db test
> db.createCollection("test") # 先創建集合,類似數據庫中的表
> show tables # show collections 命令會更加准確點
test
> db.test.drop()
true
> show tables
>
2、准備好插入的集合數據,這里使用JavaStript准備數據
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
let str = '';
for (let i = 1; i <= 99999; i++) {
str += JSON.stringify({
name: 'mongodb' + i,
age: i
});
}
document.body.innerHTML = str;
</Script>
</body>
</html>
使用瀏覽器打開上面HTML文件,復制內容生成JSON文件
3、直接使用命令插入集合
/路徑/mogodb/bin/mongoimport --db test --collection test --file /tmp/DC.json
上述命令中,首先找到mongoimport導入集合數據文件路徑,--db 后跟所選數據庫,--collection 后跟要插入到哪個集合中,--file 后跟已生成需要導入集合的數據文件,可在集合后跟--drop 參數,代表插入前清庫
4、或使用定時任務腳本按時間插入集合
#!/bin/bash
n=0
while (($n < 30)); do
/路徑/mogodb/bin/mongoimport --db test --collection test --file /tmp/DC.json
n=$((n + 1))
sleep 40
done
exit 0