×
Community Blog Hands-On Lab | Get Started with ApsaraDB for MongoDB

Hands-On Lab | Get Started with ApsaraDB for MongoDB

Part 1 of this 5-part series explains how to get started with ApsaraDB for MongoDB.

1. Get Started with ApsaraDB for MongoDB Free Trial

Once you have registered your Alibaba Cloud account and completed your account and payment information, you are ready to claim free trials of our products (such as ECS, PolarDB, RDS, and other services). You can claim all the benefits on Alibaba Cloud Free Tier Center.

If you already have existing instances for the lab, please skip this chapter.

1.  On Alibaba Cloud Free Tier Center, find ApsaraDB for MongoDB and click Try Now >

1

2.  Choose a region to deploy your MongoDB instance and complete all configurations of the free trial order. If this is your first order on Alibaba Cloud, you may need to configure a VPC and a VSwitch during the time.

2
3
4
5
6

3.  The instance will be created after placing a free tier order. It takes several minutes to complete. Come back later to check the status of the instance you just launched on the MongoDB Console by switching to the specific region that your instance is located. You can also customize the name of the instance when its status becomes Running.

7
8

2. Log on to the Database Instance

This section describes how to connect to ApsaraDB for MongoDB using Alibaba Cloud Data Management (DMS).

1.  Click ApsaraDB for MongoDB:

9

2.  On the left-side navigation pane, click Replica Set Instances:

10

3.  On the top navigation bar, select the region where the resources reside.

Description: Select the region where your MongoDB resources reside.

11

4.  On the Replica Set Instances page, find the instance you created and click Instance ID

12

5.  On the left-side navigation pane, click Account Management > Reset Password

13

6.  On the left-side navigation pane, choose Data Security > Whitelists:

14

7.  On the whitelist group list, find the default group and click Modify:

15

8.  In the Manually Modify dialog box, change the IP addresses that are allowed to access IPv4 to 0.0.0.0/0 and click OK:

16

9.  On the left-side navigation pane, click Basic Information, click Log On to Database, and click Primary:

17

10.  In the Log on to Database Instance dialog box, enter the database account and database password, and click Log on. If you forget your password, you can reset it on the Account Management page.

Parameter Description:

  1. Database Account: The account used to log on to the ApsaraDB for MongoDB instance
  2. Database Password: The password used to log on to the ApsaraDB for MongoDB instance

Description: Enter the password you reset in Step 5:

18

3. Create Databases and Users

1.  On the left-side navigation pane, click Database instance.

2.  On the Database instance section on the left, click Instances Connected. Right-click your MongoDB instance and then click Database management.

19

3.  On the Database management page, click Create DB.

20
21

4.  In the Create DB dialog box, enter a database name and click OK.

Parameter Description:

Database Name: The custom name. In this example, the database name is mymongodb.
Collection Name: Optional. The collection name is test by default.

22

As shown in the following screenshot, the database is created.

23

5.  On the left-side navigation pane, click Instances Connected. Right-click your MongoDB instance and then click Account Management.

24

6.  On the Account Management page, click Create User.

25

7.  In the Create User dialog box, select the destination database, enter the username and password, confirm your password in sequence, select Common operation role, and click OK.

Parameter Description:

Destination Database: The mymongodb database you created
Username: The custom username. In this example, the username is mytest.
Password: The custom password
Confirm Password: Enter the password again
Common Operation Role: Select read and readWrite

26

8.  Above the user list, query mymonogdb in the search box:

27

9.  You can view the information of mytest in the user list:

28

4. Create a Collection

Collections are group documents of MongoDB, similar to tables in Relational Database Management System (RDBMS). Collections exist in databases. Collections do not have a fixed structure, which means you can insert different formats and types of data into collections. Usually, the data we insert into a collection is related in some way.

1.  On the Database instance section on the left, click Instances Connected. Right-click your MongoDB instance and click Switch account:

29

2.  On the Log on to Database Instance dialog box, enter the database account, database name, and database password in sequence and click OK.

Parameter Description:
Database Account: The database account created in Step 1.3
Database Name: The database created in Step 1.3
Database Password: The password of the database created in Step 1.3

30

3.  On the SQLConsole tab, enter the following SQL statement to create a collection named testcollection and click Execution.

db.createCollection("testcollection");

31

4.  In the Execution Confirmation dialog box, click OK:

32

5.  Click the Refresh icon to view the created testcollection collection:

33

5. Operations on Documents

MongoDB Document (BSON) consists of key-value pairs. The same fields are not required in MongoDB documents, and the same data types are not required for the same fields. This is very different from relational databases and is a very prominent feature of MongoDB.

1.  Insert a document. Use the insert() method to insert documents into the collection. The syntax is listed below:

db.COLLECTION_NAME.insert(document);

Parameter Description:

COLLECTION_NAME: The name of the collection
document: The document content to be written

a) On the SQLConsole tab, enter the following SQL statement and click Execution:

db.testcollection.insert({title: 'Alibaba Cloud', 
    description: 'Alibaba Cloud official website',
    by: 'Alibaba Cloud',
    url: 'https://www.aliyun.com/',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
});

34

b) In the Execution Confirmation dialog box, click OK:

35

The following result indicates that a document has been successfully inserted:

36

2.  Query a document. Use the find() method to query documents. The syntax is listed below:

db.collection.find(query,projection);

Parameter Description:

Query: Optional. You can use a query operator to specify query conditions.
Projection: Optional. You can use a projection operator to specify the key to be returned. If you want to return all key values in a document, this parameter is not specified. This parameter is specified by default.

On the SQLConsole tab, enter the following SQL statement and click Execution:

db.testcollection.find();

37

In the Execution History below, you can see the returned result of the query:

38

3.  Update a document. Use the update() method to update documents in the collection. The syntax is in the following format:

db.collection.update(
        <query>,
        <update>,
        {
            upsert:<boolean>,
            multi:<boolean>,
            writeConcern:<document>
        }
);

Parameter Description:

Query: Required. The query condition for the update, which is similar to the condition after the where in the SQL update query
Update: Required. The update object and some update operators (such as $ and $inc), which can also be understood as the part after the set in the SQL update query
Upsert: Optional. This parameter specifies whether to insert objNew if no updated record exists. Valid values: True and False. Default value: False
Multi: Optional. This parameter specifies whether to update all records queried by conditions. Valid values: True (update all queried records) and False (update the first queried record). Default value: False
writeConcern: Optional. The level at which the exception is thrown

a) On the SQLConsole tab, enter the following SQL statement and click Execution:

db.testcollection.update({'title':'Alibaba Cloud'},{$set:{'title':'aliyun Alibaba Cloud official website'}});

39

b) In the Execution Confirmation dialog box, click OK:

40

In the Execution History below, you can see a document has been successfully updated.

41

c) On the SQLConsole tab, enter the following SQL statement and click Execution.

db.testcollection.find();

In the Execution History below, you can see the title of the document has been updated.

42

4.  Delete a document. Use the deleteMany() method to delete a document. The syntax is listed below:

db.collection.deleteMany(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

Parameter Description:

Filter: The filter condition, which is used to specify a query condition to filter all documents that meet the query condition. The delete operation is performed on the documents filtered by the query condition, which is similar to the filter condition after the where in relational databases. If you want to delete all documents in the collection, upload an empty document ({ }).
writeConcern: Optional. The value of this parameter is one document.
collation: Optional. This parameter specifies the collation used for the operation. Collation allows the user to specify language-specific strings for comparison rules.

a) On the SQLConsole tab, enter the following SQL statement and click Execution:

db.testcollection.deleteMany({ title : "aliyun Alibaba Cloud official website" });

43

b) In the Execution Confirmation dialog box, click OK.

44

In the Execution History below, you can see a document has been successfully deleted.

45

c) On the SQLConsole tab, enter the following SQL statement and click Execution:

db.testcollection.find();

In the Execution History below, you can see there are no documents in the runoob collection.

46

6. Use of MongoDB Comparison Query Operators

Comparison operators are used to compare two expressions and fetched documents from the MongoDB collection.

Comparison operators in MongoDB include:

● $gt: Greater than
● $lt: Less than
● $gte: Greater than or equal to
● $lte: Less than or equal to

1.  On the SQLConsole tab, enter the following three SQL statements and click Execution:

db.testcollection.insert({
    title: 'Alibaba Cloud official website', 
    description: 'Alibaba Cloud official website.',
    by: 'Alibaba Cloud',
    url: 'https://www.aliyun.com/',
    tags: ['aliyun1'],
    likes: 200
});
db.testcollection.insert({title: 'Help Center', 
    description: 'The URL of the Alibaba Cloud Help Center.',
    by: 'Alibaba Cloud',
    url: 'https://help.aliyun.com/',
    tags: ['aliyun2'],
    likes: 150
});
db.testcollection.insert({title: 'Experience Lab', 
    description: 'The URL of the Experience Lab',
    by: 'Alibaba Cloud',
    url: 'https://developer.aliyun.com/',
    tags: ['aliyun3'],
    likes: 100
});

47

2.  During the execution of SQL statements, the Execution Confirmation dialog box appears three times. You need to click Confirm three times:

48

In the Execution History below, you can see three documents have been successfully inserted.

49

3.  Use the $gt operator.

On the SQLConsole tab, enter the following SQL statement to obtain the data in testcollection with likes greater than 100 and then click Execution:

db.testcollection.find({likes : {$gt : 100}});

50

The execution result is listed below:

51

4.  Use the $gte operator

On the SQLConsole tab, enter the following SQL statement to obtain the data in testcollection with likes greater than or equal to 100 and then click Execution:

db.testcollection.find({likes : {$gte : 100}});

52

The execution result is listed below:

53

5.  Use the $lt operator.

On the SQLConsole tab, enter the following SQL statement to obtain the data in testcollection with likes less than 150 and then click Execution:

db.testcollection.find({likes : {$lt : 150}});

54

The execution result is listed below:

55

6.  Use the $lte operator.

On the SQLConsole tab, enter the following SQL statement to obtain the data in testcollection with likes less than or equal to 150 and then click Execution:

db.testcollection.find({likes : {$lte : 150}});

56

The execution result is listed below:

57

7. Use of MongoDB Element Query Operator: $type

The $type operator retrieves the matched data type from a collection based on the BSON type and returns the result.

On the SQLConsole tab, enter the following SQL statement to obtain the data whose title is a string in testcollection and then click Execution.

db.testcollection.find({"title" : {$type : 'string'}});

58

The execution result is listed below:

59

8. The limit() and skip() Methods of MongoDB

1.  The limit() method of MongoDB. The limit() method is used to read a specified amount of data in MongoDB. The limit() method supports a numeric parameter that specifies the number of records to read from MongoDB.

The basic syntax of the limit() method is listed below:

db.COLLECTION_NAME.find().limit(NUMBER);

On the SQLConsole tab, enter the following SQL statement to retrieve two data entries in the document and click Execution.

db.testcollection.find().limit(2);

60

The execution result is listed below:

61

2.  The skip() method of MongoDB. In addition to using the limit() method to read the specified amount of data, we can use the skip() method to skip the specified amount of data. The skip() method supports a numeric parameter as the number of skipped records.

db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER);

On the SQLConsole tab, enter the following SQL statement to retrieve a specified record in the document and skip the record and then click Execution:

db.testcollection.find().limit(1).skip(1);

62

The execution result is listed below:

63

9. Cleanup

● If you do not need to keep using it, don’t forget to clean up the test data and free trial resources in time:

Note: The duration of use for the ApsaraDB for MongoDB free trial is 30 days. If you want to extend the time of use, you can convert the free-tier resource to a paid plan by renewal at any time. Please see billing methods for more information.

If you are only using it for learning or testing purposes with a small amount of data (such as less than 5GB), you can let the resource automatically expire without doing anything. However, if you don't want to be charged under any circumstances, we strongly recommend cleaning up the resource immediately after finishing the test.

● ApsaraDB for MongoDB Resource Cleanup

Log on to the ApsaraDB for MongoDB console, select More > Switch to Pay-as-you-go in the Actions column of the ApsaraDB for MongoDB instance, and click OK.

64

Now, switch your instance to the Pay-as-you-go billing method, select More > Release in the Actions column of the ApsaraDB for MongoDB instance, and click OK:

65

0 1 0
Share on

ApsaraDB

393 posts | 74 followers

You may also like

Comments

ApsaraDB

393 posts | 74 followers

Related Products