All Products
Search
Document Center

PolarDB:Use document database (MongoDB-compatible)

Last Updated:Jul 28, 2026

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.

Note

You can go to PolarDB console and view the versions on the Settings and Management > Version Management 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.

  1. On the Settings and Management > Accounts page of the cluster, click Create Account.

  2. Set Account Type to Document Database Privileged Account. The account name is fixed as doc_root. Then, set a password.

  3. After the account is created, it appears in the account list.

    Note
    • Document 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_root without 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.

    Note

    Accessing 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

  1. Install the mongosh client: mongosh is the official command-line tool recommended by MongoDB. This topic uses an ECS instance running Alibaba Cloud Linux release 3 as an example.

    1. Run the following command to create a YUM repository file.

      sudo vim /etc/yum.repos.d/mongodb-org-6.repo
    2. Paste 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.asc
    3. Run the following installation command.

      sudo yum install -y mongodb-org
  2. 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.

  3. Verify read and write operations.

    1. 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 ObjectId values of the inserted documents.

      {
        acknowledged: true,
        insertedIds: {
          '0': ObjectId('6926c9a36625af7c339xxx'),
          '1': ObjectId('6926c9a36625af7c339xxx'),
          '2': ObjectId('6926c9a36625af7c339xxx')
        }
      }
    2. Run the following command to query the inserted data.

      db.users.find({
        age: {
          $gt: 25 
        } 
      })

      If the record for Bob is 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.

  1. Go to your project directory as needed. This example uses /home/testMongoDB.

    mkdir /home/testMongoDB
    cd /home/testMongoDB
  2. In the /home/testMongoDB directory, create a virtual environment (venv) to isolate project dependencies and avoid global pollution.

    python3 -m venv myenv
  3. Activate the virtual environment.

    source myenv/bin/activate
  4. Install the required Python dependencies.

    pip3 install pymongo
  5. Create a Python file and copy the following code into it. Replace endpoint_url, username, and password with the document database endpoint and dedicated document database account of your PolarDB cluster.

    vim main.py
    from 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()
  6. After you run the script, you should see output similar to the following:

    python3 main.py
    Connected 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 successfully

    This output indicates that you have successfully connected to and operated the document database. All configurations are in effect.