This topic describes how to create a database and a collection in an ApsaraDB for MongoDB instance and write data to the collection.
Prerequisites
You have connected to the instance by following the quick start steps.
Procedure
DMS
-
Create a database named
test.Run the following command and click Execute.
use testAfter running the command, the result pane displays the following message:
The current switch is invalid. Open a new test tab to proceed.After the database is created, click the database name in the Execution Result tab to switch to that database.
-
In the
testdatabase, create a collection namedmongo.Run the following command and click Execute. If the Execution Confirmation dialog box appears, click Confirm.
db.createCollection("mongo")If the
okfield in the result is1.0, the collection is created. Other values indicate failure. -
Insert two documents,
{"name": "test"}and{"count": "10"}, into themongocollection.Run the following command and click Execute. If the Execution Confirmation dialog box appears, click Confirm.
db.runCommand({insert: "mongo", documents: [{"name": "test"},{"count": "10"}]})After the command runs, the result shows an
nInsertedvalue of 2, indicating that two documents were inserted. -
Query the documents in the
mongocollection.Run the following command and click Execute.
db.getCollection("mongo").find({})After the command runs, the JSON view displays the two returned documents: one containing
name: "test"and the other containingcount: "10".
MongoDB shell
-
Create and switch to the
testdatabase.use test -
In the
testdatabase, create a collection namedmongo.db.createCollection("mongo")If the
okfield in the result is1.0, the collection is created. Other values indicate failure. -
Insert two documents,
{"name": "test"}and{"count": "10"}, into themongocollection.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 }) } -
Query the documents in the
mongocollection.db.getCollection("mongo").find({})mgset-xxxxxxxx [primary] test> db.getCollection("mongo").find({}) [ { _id: ObjectId('682beb626f94807446850cc1'), name: 'test' }, { _id: ObjectId('682beb626f94807446850cc2'), count: '10' } ]