This topic guides you through the entire process from creating a cluster to making your first successful connection, helping you get started with the document database compatibility feature of PolarDB for MySQL.
Scope of application
Before you use document database compatibility with the MongoDB protocol, make sure that your cluster meets the following version requirements:
Kernel version: MySQL 8.0.2, and the minor kernel version must be 8.0.2.2.36 or later.
PolarProxy version: 2.9.22 or later.
Other limits: Multi-master cluster (Limitless) and Serverless clusters do not support document database compatibility.
You can go to PolarDB console and view the versions on the page of your cluster. If the versions do not meet the requirements, upgrade the minor version.
Enable the document database compatibility feature
You can enable the document database compatibility feature for your cluster in the following ways. If your cluster meets the scope of application, you can find the Document Database Compatibility configuration item on the Basic Information page of the cluster, and then click Enable.
Configure a document database endpoint
After you enable the document database compatibility feature, the system automatically creates a default document database endpoint. You can also create a custom endpoint to meet specific requirements.
In the Database Connections section on the Basic Information page of the cluster, you can find the default Endpoint for Document Database.
(Optional) Click Create Custom Cluster Endpoint and set the endpoint type to Endpoint for Document Database.
Create a dedicated document database account
You need to create a dedicated document database account to connect to the document database.
On the page of the cluster, click Create Account.
Set Account Type to Document Database Privileged Account. The account name is fixed as
doc_root. Then, set a password.After the account is created, it appears in the account list.
NoteDocument database accounts are created within the context of a specific database. Different databases may have accounts with the same name. Therefore, the corresponding account in PolarDB for MySQL has a prefix to distinguish between different databases. When you log on, use the account name
doc_rootwithout the prefix.The console only supports creating privileged document database accounts. To create a standard document database account, connect to the document database endpoint and run the createUser command.
Configure network access
Choose a network connection method based on the location of your server or client.
Private connection (recommended)
If your application is deployed on an Alibaba Cloud ECS instance, make sure that the ECS instance and the PolarDB cluster are in the same VPC, and add the IP address or security group of the ECS instance to the whitelist of the cluster.
Public connection
If you want to develop and test in a local environment, or if the ECS instance and the PolarDB cluster are not in the same VPC, you can apply for a public endpoint for the Endpoint for Document Database in the Database Connections section on the Basic Information page of the cluster.
NoteAccessing a public endpoint increases security risks. We recommend that you use public endpoints only for temporary development and testing, and release the public endpoint promptly after use.
Connect and verify
After you complete the preceding configurations, you can use an application or a client tool such as mongosh to connect to the database and verify the feature.
mongosh client
Install the
mongoshclient:mongoshis the official command-line tool recommended by MongoDB. This topic uses an ECS instance runningAlibaba Cloud Linux release 3as an example.Run the following command to create a YUM repository file.
sudo vim /etc/yum.repos.d/mongodb-org-6.repoPaste the following content into the file.
[mongodb-org-6.0] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/6.0/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://pgp.mongodb.com/server-6.0.ascRun the following installation command.
sudo yum install -y mongodb-org
Connect to the database: Use the following command format and replace the placeholders with your actual values.
mongosh "mongodb://<username>:<password>@<polardb_endpoint>:<port>"Parameters:
<username>: the document database account name.<password>: the password for the document database account. If the password contains special characters such as@,#, or$, URL-encode the password first to prevent parsing errors in the connection string.<polardb_endpoint>: the document database endpoint.<port>: the port number for the document database endpoint.
Connection example:
# Assume the account is doc_user, the password is YourPassword123!, the endpoint is pe-****************.rwlb.rds.aliyuncs.com, and the port is 3306 mongosh "mongodb://doc_user:YourPassword123!@pe-****************.rwlb.rds.aliyuncs.com:3306"After a successful connection, the command prompt changes to
test>or a similar format.Verify read and write operations.
Run the following command to insert multiple documents.
db.users.insertMany([ { name: "Alice", age: 25, email: "alice@example.com" }, { name: "Bob", age: 30, email: "bob@example.com" }, { name: "Charlie", age: 22, email: "charlie@example.com" } ])If the operation is successful, the system returns a confirmation message and the
ObjectIdvalues of the inserted documents.{ acknowledged: true, insertedIds: { '0': ObjectId('6926c9a36625af7c339xxx'), '1': ObjectId('6926c9a36625af7c339xxx'), '2': ObjectId('6926c9a36625af7c339xxx') } }Run the following command to query the inserted data.
db.users.find({ age: { $gt: 25 } })If the record for
Bobis returned, the document database compatibility feature is enabled and configured correctly for the PolarDB for MySQL cluster. Read and write operations are working as expected.[ { name: 'Bob', age: 30, email: 'bob@example.com', _id: ObjectId('6926c9a36625af7c339xxx') } ]
Python example
Use the following Python sample code with the pymongo SDK to verify your configuration. This example uses an ECS instance running the Alibaba Cloud Linux 3.2104 LTS 64-bit operating system.
Go to your project directory as needed. This example uses
/home/testMongoDB.mkdir /home/testMongoDB cd /home/testMongoDBIn the
/home/testMongoDBdirectory, create a virtual environment (venv) to isolate project dependencies and avoid global pollution.python3 -m venv myenvActivate the virtual environment.
source myenv/bin/activateInstall the required Python dependencies.
pip3 install pymongoCreate a Python file and copy the following code into it. Replace
endpoint_url,username, andpasswordwith the document database endpoint and dedicated document database account of your PolarDB cluster.vim main.pyfrom pymongo import MongoClient # 1. Configure your connection details # Endpoint URL from Step 2 endpoint_url = "mongodb://<your-polardb-documentdb-endpoint>:<port>" # username from Step 3 username = "<your-username>" # password from Step 3 password = "<your-password>" def insert_data(userinfo): """Insert data into collection""" users = [ {"_id": 1, "userid": "user01", "name": "Alice", "age": 18}, {"_id": 2, "userid": "user02", "name": "Bob", "age": 25}, {"_id": 3, "userid": "user03", "name": "Charlie", "age": 20}, ] userinfo.insert_many(users) print("Inserted %d documents into the collection" % len(users)) def find_data(userinfo): """Find data from collection""" users = userinfo.find() print("Found user info from collection") for user in users: print(user) def find_data_by_age(userinfo): """Find data by age from collection""" users = userinfo.find({"age": {"$gte": 20}}) print("Found user info with age >= 20 from collection") for user in users: print(user) # Run the verification process if __name__ == "__main__": try: # 2. Create a MongoDB client client = MongoClient(endpoint_url, username=username, password=password) print("Connected to PolarDB DocumentDB successfully") database = client.get_database("test") userinfo = database.get_collection("userinfo") # 3. Insert some data and verify it insert_data(userinfo) find_data(userinfo) find_data_by_age(userinfo) finally: # Ensure the collection is cleaned up even if errors occur userinfo.drop() print("Collection deleted successfully") client.close()After you run the script, you should see output similar to the following:
python3 main.pyConnected to PolarDB DocumentDB successfully Inserted 3 documents into the collection Found user info from collection {'_id': 1, 'userid': 'user01', 'name': 'Alice', 'age': 18} {'_id': 2, 'userid': 'user02', 'name': 'Bob', 'age': 25} {'_id': 3, 'userid': 'user03', 'name': 'Charlie', 'age': 20} Found user info with age >= 20 from collection {'_id': 2, 'userid': 'user02', 'name': 'Bob', 'age': 25} {'_id': 3, 'userid': 'user03', 'name': 'Charlie', 'age': 20} Collection deleted successfullyThis output indicates that you have successfully connected to and operated the document database. All configurations are in effect.