本文介紹如何在ApsaraDB for MongoDB中建立資料庫和集合并寫入資料。
前提條件
已根據快速入門步驟成功串連執行個體。
操作步驟
DMS
-
建立
test資料庫。輸入以下命令,單擊执行。
use test執行後,結果區提示:
當前 switch 無效,請新開test進行操作。成功建立資料庫後,單擊执行结果中的資料庫名,跳轉至目標資料庫環境。
-
在
test資料庫中建立mongo集合。輸入以下命令,單擊执行。如彈出執行確認對話方塊中,單擊确认。
db.createCollection("mongo")返回結果中
ok取值為1.0時,表示建立成功,其他取值表示建立失敗。 -
將兩組資料
{"name": "test"}和{"count": "10"}寫入mongo集合。輸入以下命令,單擊执行。如彈出執行確認對話方塊中,單擊确认。
db.runCommand({insert: "mongo", documents: [{"name": "test"},{"count": "10"}]})執行成功後,返回結果中
nInserted的值為 2,表示成功插入了 2 條文檔。 -
查詢
mongo集合中的資料。輸入以下命令,單擊执行。
db.getCollection("mongo").find({})執行成功後,結果地區以 JSON 視圖展示返回的兩條文檔:第一條含欄位
name: "test",第二條含欄位count: "10"。
MongoDB Shell
-
建立並切換至
test資料庫。use test -
在
test資料庫中建立mongo集合。db.createCollection("mongo")返回結果中
ok取值為1.0時,表示建立成功,其他取值表示建立失敗。 -
將兩組資料
{"name": "test"}和{"count": "10"}寫入mongo集合。db.runCommand({insert: "mongo", documents: [{"name": "test"},{"count": "10"}]})mgset-80xxx [primary] test> db.runCommand({insert: "mongo", documents: [{"name": "test"},{"count": "10"}]}) { n: 2, electionId: ObjectId('7fffffff0000000000000001'), opTime: { ts: Timestamp({ t: 1747708770, i: 1 }), t: Long('1') }, ok: 1, '$clusterTime': { clusterTime: Timestamp({ t: 1747708770, i: 1 }), signature: { hash: Binary.createFromBase64('xDyGfZsHUuJXLQE5vgX18karcl0=', 0), keyId: Long('7506346035782877189') } }, operationTime: Timestamp({ t: 1747708770, i: 1 }) } -
查詢
mongo集合中的資料。db.getCollection("mongo").find({})mgset-xxxxxxxx [primary] test> db.getCollection("mongo").find({}) [ { _id: ObjectId('682beb626f94807446850cc1'), name: 'test' }, { _id: ObjectId('682beb626f94807446850cc2'), count: '10' } ]