本文介绍如何在云数据库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' } ]