1
头图

Amazon DocumentDB (MongoDB compatible) is a fast, scalable, and highly available fully managed document database service that supports MongoDB workloads. Today, we announced that Amazon DocumentDB has officially acquired MongoDB 4.0 compatibility. With this upgrade, you can now use atomicity, consistency, isolation, and durability (ACID) transactions, open change stream cursors for databases or clusters, and more. For the complete release notes of Amazon DocumentDB 4.0, see MongoDB 4.0 compatibility .

In this article, we will , and show you how to use Amazon DocumentDB 4.0 and transaction on the Amazon Cloud9 environment.

📢 To learn more about the latest technology releases and practical innovations of Amazon Cloud Technology, stay tuned to the 2021 Amazon Cloud Technology China Summit held in Shanghai, Beijing and Shenzhen! Click on the picture to sign up~

New features in Amazon DocumentDB 4.0

The following are the main features introduced by Amazon DocumentDB 4.0. To see the complete list of new features, see MongoDB 4.0 compatibility .

ACID transactions-Amazon DocumentDB can now support transactions across multiple documents, statements, collections, and databases. Transaction support enables you to perform ACID operations across one or more documents in an Amazon DocumentDB cluster, thereby simplifying the application development process. For more details, see transaction .

1. Change flow-You can now open the change flow at the cluster level (client.watch() or mongo.watch()) or the database level (db.watch()). You can also specify a startAtOperationTime to open the change stream cursor and extend the retention period of the change stream to 7 days (previously, it was up to 24 hours). For more details, see Using Change Flow Amazon DocumentDB.

2. Amazon DMS-You can now use Amazon Database Migration Service (Amazon DMS) to migrate MongoDB 4.0 workloads to Amazon DocumentDB 4.0. Amazon DMS can now support MongoDB 4.0 as the source, Amazon DocumentDB 4.0 as the target, and Amazon DocumentDB 3.6 as the source to complete the upgrade from version 3.6 to version 4.0. For more details, see Use Amazon DocumentDB as the target of Amazon Database Migration Service .

3. Monitoring – By adding transactions, you can now use five new Amazon CloudWatch metrics:

TransactionsOpen, TransactionsOpenMax, TransactionsAborted, TransactionsStarted and TransactionsCommitted, plus new fields such as currentOp, ServerStatus and profiler. For more details, see use Amazon CloudWatch monitoring DocumentDB Amazon .

4. Performance and indexing-the new version also contains a number of performance and index improvements: the index can be used in the $lookup aggregation stage, the index (the query involved) can directly provide the find() query with projection, and the findAndModify API can be used Use hint() to optimize the performance of the $addToSet operator, while improving and reducing the overall index size. For more details, please refer to the release note .

5. Operators-We have added support for the following new aggregation operators: $ifNull, $replaceRoot, $setIsSubset, $setInstersection, $setUnion and $setEquals. For more details, see support MongoDB API, operations and data types .

6. Role-based access control (RBAC)-using the ListCollection and ListDatabase commands, you can now choose to use the authorizedCollections and authorizedDatabases parameters to allow users to list the collections and databases that they have access to, so there is no need to use listCollections and listCollections and listDatabase role. Users can also end their cursors directly without using the KillCursor role. For more details, see Use role-based access control (built-in roles) to restrict database access behavior .

Amazon DocumentDB4.0 and Transaction Getting Started Guide

The first step is to create an Amazon Cloud9 environment plus an Amazon DocumentDB cluster Amazon Virtual Private Cloud For instructions on creating a default VPC, please refer to the Amazon VPC Getting Started Guide. This article will demonstrate how to use the mongo shell to connect to an Amazon DocumentDB cluster from the Amazon Cloud9 environment and run transactions. When creating Amazon resources, we recommend that you follow Amazon Identity and Access Management (IAM) best practices.

The figure below shows the final structure of this exercise.

In this walkthrough, please use the default VPC in a specific region. For more details, please refer to create a Virtual Private Cloud (VPC) .

Create Amazon Cloud9 environment

To create an Amazon Cloud9 environment, complete the following steps:

1. On the Amazon Cloud9 console , select Create environment.

2. In the Name section under Environment name and description, enter a name for the environment. This article named the environment Amazon DocumentDB Cloud9.

3. Choose Next step.

4. In the Configure settings section, directly use all the default options.

5. Choose Next step.

6. In the Review section, select Create environment.

The provisioning of the Amazon Cloud9 environment may take up to 3 minutes. After finishing, you will see the following command prompt.

You will be redirected to the command prompt, where you install the mongo shell and connect to the Amazon DocumentDB cluster.

Create security group

In this step, you will use Amazon Elastic Compute Cloud (Amazon EC2) to create a new security group to connect to the Amazon DocumentDB cluster from port 27017 in the Amazon Cloud9 environment (the default port of Amazon DocumentDB).

1. Under Amazon EC2 console, select Security groups.

2. Select Create security group.

3. In the Security group name section, enter demoDocDB.

4. In the VPC section, accept to use your default VPC.

5. In the Description section, enter the corresponding description.

6. In the Inbound rules section, select Add rule.

7. In the Type section, select Custom TCP Rule.

8. In the Port Range section, enter 27017. The source security group is the security group you just created for the Amazon Cloud9 environment.

9. To view the list of available security groups, enter cloud9 in the target field.

10. Select the security group named amazon-cloud9-.

11. Accept all the default options, and then select Create security group.

The following figure shows the security group you created in this step and the Amazon Cloud9 security group created when you created the Amazon Cloud9 environment.

Create an Amazon DocumentDB 4.0 cluster

To create your Amazon DocumentDB 4.0 cluster, complete the following steps:

1. On Amazon DocumentDB console , select Create.

2. In the Engine version section, select the default version (4.0.0).

3. In the Instance class section of the Create Amazon DocumentDB cluster page, select t3.medium.

4. In the Number of instances section, select 1. Used to control costs to the lowest level.

5. All other settings are left as default options.

6. In the Authentication section, enter the user name and password.

7. Open Show advanced settings.

8. In the VPC security groups in the Network settings section, select demoDocDB.

9. Choose Create cluster.

Amazon DocumentDB will now configure your cluster, which may take a few minutes to complete. When the cluster and instance status are both displayed as Available, you can access the cluster. During the Amazon DocumentDB cluster setup process, please complete the remaining steps to connect to the Amazon DocumentDB cluster.

install 4.0 mongo shell

Now, you can install the mongo shell and use this command-line utility to access and query your Amazon DocumentDB cluster.

1. Under Your environments in the Amazon Cloud9r console, select Amazon DocumentDBCloud9. Choose Open IDE.

2. To install the 4.0 mongo shell, use the following command in the command prompt to create a repo file: echo -e "[mongodb-org-4.0] \nname=MongoDB Repository\nbaseurl= https://repo.mongodb.org /yum/amazon/2013.03/mongodb-org/4.0/x86_64/ \ngpgcheck=1 \nenabled=1 \ngpgkey= https://www.mongodb.org/static/pgp/server-4.0.asc" | sudo tee /etc/yum.repos.d/mongodb-org-4.0.repo

3. After completion, use the following command to install the mongo shell: sudo yum install-y mongodb-org-shell

The Transport Layer Security (TLS) protocol will be enabled by default on the Amazon DocumentDB cluster. For more details, see Manage Amazon DocumentDB Cluster TLS Settings .

To transmit encrypted data, as DocumentDB Amazon CA certificate , specific code as follows:

wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem

to your Amazon DocumentDB cluster

Now you can connect to your Amazon DocumentDB cluster.

1. Find your cluster on the Clusters page of the Amazon DocumentDB console. The docdb-2020-10-09-21-45-11 cluster is used in this article.

2. Select the cluster you created.

3. Copy the corresponding connection string. Please ignore the <insertYourPassword> part so that the mongo shell will prompt you to enter the password when you connect. This way, you don’t have to enter the password in clear text.

Your connection string should resemble the screenshot below.

4. When you enter the password, you will see the rs0:PRIMARY> prompt, which means you have successfully connected to the Amazon DocumentDB cluster.

For more detailed information about troubleshooting, see Amazon DocumentDB Troubleshooting .

After accessing the mongo shell, you can use the following command to confirm the current version (4.0.0):

db.version()

The output is as follows:

4.0.0

Use transaction

Now that you have successfully connected to the cluster using the mongo shell, you can use transactions next. Here we use a typical transaction use case, that is, borrow money from someone's account and deposit the money into another person's account. Since this use case requires the use of two separate operations in the database, we hope that the two operations will be completed in the same transaction and follow the ACID principle. In this exercise, we transfer $400 from Bob's bank account to Alice's bank account. The initial balance of both accounts is $500.

  • In order to start with an empty set, we first delete the account set:

db.account.drop()

You will get the following output:

{true, false}

  • Insert data into the collection to represent Bob's account:
db.account.insert({"_id": 1, "name": "Bob", "balance": 500.00});

You will get the following output:

WriteResult({ "nInserted" : 1 })

  • Insert data into the collection to represent Alice's account:
db.account.insert({“_id”: 2, “name”: “Alice”, “balance”: 500.00});

You will get the following output:

WriteResult({ “nInserted” : 1 })

  • To start a transaction, create a session and session object for the account:
var mySession =getMongo().startSession();6. var mySessionObject = mySession.getDatabase('test').getCollection('account');

mySession.startTransaction({readConcern: {level: 'snapshot'}, writeConcern: {w: 'majority'}});
  • In this transaction, borrow $400 from Bob's account:
mySessionObject.updateOne({"_id": 2}, {"$inc": {"balance": 400}}); 

You will get the following output:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
  • Similarly, add 400 USD to Alice's account:
mySessionObject.updateOne({"_id": 1}, {"$inc": {"balance": -400}});

You will get the following output:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
  • In this transaction, you can use the following code to check the update status of the two accounts:
    mySessionObject.find()

You will get the following output:

{ "_id" : 2, "name" : "Alice", "balance" : 900 }

{ "_id" : 1, "name" : "Bob", "balance" : 100 }
  • If you look outside the transaction, you will find that the update result has not yet been displayed:

db.account.find()

You will get the following output:

{ "_id" : 1, "name" : "Alice", "balance" : 500 }

{ "_id" : 2, "name" : "Bob", "balance" : 500 }
  • Commit the transaction and close the session:
  • To view the update results, use the following code:

db.account.find()

You will get the following output:

{ "_id" : 2, "name" : "Alice", "balance" : 900 }

{ "_id" : 1, "name" : "Bob", "balance" : 100 }

resource cleanup

After completing the exercise, you should stop or delete the Amazon DocumentDB cluster to reduce costs. By default, after a 30-minute idle period, your Amazon Cloud9 environment will stop running basic EC2 instances to help save costs.

summary

This article introduces you to the MongoDB 4.0 compatibility in Amazon DocumentDB, and shows how to create an Amazon Cloud9 environment, install a mongo 4.0 shell, create an Amazon DocumentDB cluster, access the cluster, and use Amazon DocumentDB 4.0 and transactions through simple use cases. For more details, see MongoDB 4.0 compatibility and transaction . For detailed information about the latest published content and blog posts, please refer to the Amazon DocumentDB (MongoDB compatible) resource .

Author of this article


Joseph Idziorek
Amazon Cloud Technology Chief Product Manager


亚马逊云开发者
2.9k 声望9.6k 粉丝

亚马逊云开发者社区是面向开发者交流与互动的平台。在这里,你可以分享和获取有关云计算、人工智能、IoT、区块链等相关技术和前沿知识,也可以与同行或爱好者们交流探讨,共同成长。


引用和评论

0 条评论