MongoDB使用sh或者js檔案

來源:互聯網
上載者:User

標籤:MongoDB使用sh或者js檔案

有時候我們需要向資料庫中手動插入一些資料,但是如果資料格式本身比較複雜,並且需要插入多條資料的時候,直接子啊mongodb的shell上寫js代碼來像執行命令一樣,雖然簡單粗暴,但是對於比較複雜資料的情況是很不方便的,並且在shell上寫js代碼不方便修改資料等。

所以如果能把想要執行的js代碼寫成一個指令碼,需要插入、修改資料的時候,只需要執行這個指令碼就可以了,並且修改js代碼也非常的方便


例如:在testdb資料庫下的test集合中插入一條資料, 

在任意路徑下建立一個insert.js的檔案(檔案名稱自己定義),內容如下:

var url="mongodb://localhost:27019/testdb";var db = connect(url);db.test.insert({"name":"user5"});


執行:

# mongo insert.js MongoDB shell version v3.4.14connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.14connecting to: mongodb://localhost:27019/testdbMongoDB server version: 3.4.14


查看結果:

test-set:PRIMARY> db.test.find(){ "_id" : ObjectId("5ad844efa46a748c5a90fe41"), "name" : "user1" }{ "_id" : ObjectId("5ad8608a8de9df222390480e"), "name" : "user2" }{ "_id" : ObjectId("5ad860998de9df222390480f"), "name" : "user3" }{ "_id" : ObjectId("5ad860ba349d15f7f4a9ce9b"), "name" : "user4" }{ "_id" : ObjectId("5ad860be8c80e45b6ab87b90"), "name" : "user4" }{ "_id" : ObjectId("5ad860c0049eccbc93be69b0"), "name" : "user4" }{ "_id" : ObjectId("5ad8611c7d1d4c1131c1a424"), "name" : "user4" }{ "_id" : ObjectId("5ad8625a16805ab661da90ea"), "name" : "user5" }

資料插入成功。


還可以寫成shell指令碼,

use testdb;db.test.insert({"name":"user4"});

執行:

# mongo --port 27019 < test.sh       MongoDB shell version v3.4.14connecting to: mongodb://127.0.0.1:27019/MongoDB server version: 3.4.14switched to db testdbWriteResult({ "nInserted" : 1 })bye


注意:執行shell指令碼和js指令碼不一樣的,js檔案中定義了mongdb的url地址。shell指令碼是將檔案內容作為輸入,輸入到命令列。js指令碼中不能使用use db_name這樣的語句。



MongoDB使用sh或者js檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.