百度智能云

All Product Document

          Cloud Database MONGODB

          Connect to MongoDB Instance Through Program Code

          Baidu Could Database MongoDB is fully compatible with the MongoDB protocol. This article introduces examples of various programs connecting to the database.

          Preparations

          • Acquire the cloud database MongoDB connection address according to your instance type.
          • Download and install the official driver according to your language. For more information, see MongoDB Drivers.

          Descriptions:

          • The connection Demo given in this article is only applicable to the MongoDB intranet connection address provided by Baidu Cloud.
          • During the connection to a sharded cluster instance, you do not need to specify the replicaSet related parameters in the following Demo.

          Node.js Linking Example

          Related link: MongoDB Node.js Driver.

          1. Initialize the item.
          mkdir node-mongodb-demo
          cd node-mongodb-demo
          npm init
          1. Install the driver package and toolkit.
          npm install mongodb node-uuid sprintf-js
          1. Get the MongoDB connection information of the cloud database MongoDB according to your instance type.
          2. Node.js Demo Code.
          var host1 = "*********.mongodb.gz.baidubce.com";
          var port1 = 27017;
          var host2 = "*********.mongodb.gz.baidubce.com";
          var port2 = 27017;
          var username = "root";
          var password = "******";
          var replSetName = "rep-******";
          var adminDb = 'admin'
          var demoDb = "test";
          var demoColl = "testColl";
          // The official recommended solution.
          var url = sprintf("mongodb://%s:%s@%s:%d,%s:%d/%s?replicaSet=%s", username, password, host1, port1, host2, port2, adminDb, replSetName);
          console.info("url:", url);
          //Get mongoClient.
          mongoClient.connect(url, {useUnifiedTopology: true, useNewUrlParser: true}, function (err, db) {
              	if (err) {
                  	console.error("connect err:", err);
                  	return 1;
             	 }
                  //Get the Collecton handle.
                  var collection = db.db(demoDb).collection(demoColl);
                  var demoName = "NODE:" + uuid.v1();
                  var doc = { "DEMO": demoName, "MESG": "Hello BaiduCoudDB For MongoDB"};
                  console.info("ready insert document: ", doc);
                  // Insert data
                  collection.insertOne(doc, function (err, data) {
                      if (err) {
                          console.error("insert err:", err);
                          return 1;
                      }
                      console.info("insert result:", data["result"]);
                      // Read data
                      var filter = { "DEMO": demoName };
                      collection.find(filter).toArray(function (err, items) {
                          if (err) {
                              console.error("find err:", err);
                              return 1;
                          }
                          console.info("find document: ", items);
                          //Close the Client and release resources.
                          db.close();
                  });
              });
          });

          PHP Linking Examples

          Related link: MongoDB PHP Driver.

          1. Install the driver package and toolkit.
          $ pecl install mongodb
          $ echo "extension=mongodb.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`
          $ composer require "mongodb/mongodb=^1.0.0"
          1. Obtain the cloud database MongoDB connection information.
          2. PHP Demo Code.
          <?php
          require 'vendor/autoload.php'; // include Composer goodies
          # Instance Information
          $demo_seed1 = '*********.mongodb.gz.baidubce.com:27017';
          $demo_seed2 = '*********.mongodb.gz.baidubce.com:27017';
          $demo_replname = "rep-******";
          $demo_user = 'root';
          $demo_password = '*********';
          $demo_db = 'admin';
          # Construct the mongodb connection string based on the instance information.
          # mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
          $demo_uri = 'mongodb://' . $demo_user . ':' . $demo_password . '@' .
              $demo_seed1 . ',' . $demo_seed2 . '/' . $demo_db . '?replicaSet=' . $demo_replname;
          echo "demo_uri = '$demo_uri'", "\n";
          $client = new MongoDB\Client($demo_uri);
          $collection = $client->testDb->testColl;
          $result = $collection->insertOne(['name' => 'DocDB for Mongodb', 'desc' => 'Hello, Mongodb']);
          echo "Inserted with Object ID '{$result->getInsertedId()}'", "\n";
          $result = $collection->find(['name' => 'DocDB for Mongodb']);
          foreach ($result as $entry) {
              echo $entry->_id, ': ', $entry->name, "\n";
          }
          ?>

          Java Linking Example

          Related link: Download Jar package.

          1. Obtain the cloud database MongoDB connection information.
          2. Java Demo Code.
          • Maven Configuration
          <dependencies>
              <dependency>
                  <groupId>org.mongodb</groupId>
                  <artifactId>mongo-java-driver</artifactId>
                  <version>3.6.4</version>
              </dependency>
          </dependencies>
          • Java Code.
          import java.util.ArrayList;
          import java.util.List;
          import java.util.UUID;
          
          import com.mongodb.*;
          import com.mongodb.client.MongoCollection;
          import com.mongodb.client.MongoCursor;
          import com.mongodb.client.MongoDatabase;
          import org.bson.BsonDocument;
          import org.bson.BsonString;
          import org.bson.Document;
          
          public class App {
              public static ServerAddress seed1 = new ServerAddress("*********.mongodb.gz.baidubce.com",
                      27017);
              public static ServerAddress seed2 = new ServerAddress("*********.mongodb.gz.baidubce.com",
                      27017);
              public static String username = "root";
              public static String password = "*********";
              public static String ReplSetName = "rep-******";
              public static String DEFAULT_DB = "admin";
              public static String DEMO_DB = "test";
              public static String DEMO_COLL = "testColl";
              public static MongoClient createMongoDBClient() {
                  // Build a Seed list.
                  List<ServerAddress> seedList = new ArrayList<ServerAddress>();
                  seedList.add(seed1);
                  seedList.add(seed2);
                  // Build the authentication information.
                  List<MongoCredential> credentials = new ArrayList<MongoCredential>();
                  credentials.add(MongoCredential.createScramSha1Credential(username, DEFAULT_DB,
                          password.toCharArray()));
                  // Build the operation options. The options beyond the requiredReplicaSetName attribute are configured according to their actual requirements, and the default parameters meet most scenarios.
                  MongoClientOptions options = MongoClientOptions.builder().requiredReplicaSetName(ReplSetName)
                          .socketTimeout(2000).connectionsPerHost(1).build();
                  return new MongoClient(seedList, credentials, options);
              }
              public static MongoClient createMongoDBClientWithURI() {
                  // The other type is initialized by URI.
                  // mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
                  MongoClientURI connectionString = new MongoClientURI("mongodb://" + username + ":" + password + "@"
                          + seed1 + "," + seed2 + "/" + DEFAULT_DB + "?replicaSet=" + ReplSetName);
                  return new MongoClient(connectionString);
              }
              public static void main(String args[]) {
                  MongoClient client = createMongoDBClient();
                  // or
                  // MongoClient client = createMongoDBClientWithURI();
                  try {
                      // Get the Collecton handle.
                      MongoDatabase database = client.getDatabase(DEMO_DB);
                      MongoCollection<Document> collection = database.getCollection(DEMO_COLL);
                      // Insert data
                      Document doc = new Document();
                      String demoname = "JAVA:" + UUID.randomUUID();
                      doc.append("DEMO", demoname);
                      doc.append("MESG", "Hello DocDB For MongoDB");
                      collection.insertOne(doc);
                      System.out.println("insert document: " + doc);
                      // Read data
                      BsonDocument filter = new BsonDocument();
                      filter.append("DEMO", new BsonString(demoname));
                      MongoCursor<Document> cursor = collection.find(filter).iterator();
                      while (cursor.hasNext()) {
                          System.out.println("find document: " + cursor.next());
                      }
                  } finally {
                      // Close the Client and release resources.
                      client.close();
                  }
                  return;
              }
          }

          Python Linking Example

          Related link: pymongo download address

          1. Install pymongo.
          pip install pymongo

          2. Obtain the MongoDB connection information of the cloud database.
          3.Python Demo Code。

          import uuid
          from pymongo import MongoClient
          CONN_ADDR1 = '*********.mongodb.gz.baidubce.com:27017'
          CONN_ADDR2 = '*********.mongodb.gz.baidubce.com:27017'
          REPLICAT_SET = 'rep-******'
          username = 'root'
          password = '*********'
          client = MongoClient([CONN_ADDR1, CONN_ADDR2], replicaSet=REPLICAT_SET)
          client.admin.authenticate(username, password)
          demo_name = 'python-' + str(uuid.uuid1())
          print 'demo_name:', demo_name
          doc = dict(DEMO=demo_name, MESG="Hello DocDB For MongoDB")
          doc_id = client.test.testColl.insert(doc)
          print 'doc_id:', doc_id
          for d in client.test.testColl.find(dict(DEMO=demo_name)):
              print 'find documents:', d

          C# Linking Example

          Related link: MongoDB C# Driver.

          1. Install the following driver package.
          mongocsharpdriver.dll
          1. Obtain the MongoDB connection information of the cloud database.
          2. C# Demo Code。
          using MongoDB.Driver;
          using System;
          using System.Collections.Generic;
          
          namespace Baiduyun
          {
              class Program
              {
                  static void Main(string[] args)
                  {
                      //Mongo Instance Information
                      const string host1 = "*********.mongodb.gz.baidubce.com";
                      const int port1 = 27017;
                      const string host2 = "*********.mongodb.gz.baidubce.com";
                      const int port2 = 27017;
                      const string replicaSetName = "rep-******";
                      const string admin = "admin";
                      const string userName = "root";
                      const string passwd = "*********";
          
                      try
                      {
                          Console.WriteLine("Start the connection.......");
                          MongoClientSettings settings = new MongoClientSettings();
                          List<MongoServerAddress> servers = new List<MongoServerAddress>();
                          servers.Add(new MongoServerAddress(host1, port1));
                          servers.Add(new MongoServerAddress(host2, port2));
                          settings.Servers = servers;
                          // Set a replica cluster name
                          settings.ReplicaSetName = replicaSetName;
                          // Set the timeout period to 3 seconds
                          settings.ConnectTimeout = new TimeSpan(0, 0, 0, 3, 0);
                          MongoCredential credentials = MongoCredential.CreateCredential(admin, userName, passwd);
                          settings.Credential = credentials;
                          MongoClient client = new MongoClient(settings);
                          var server = client.GetServer();
                          MongoDatabase database = server.GetDatabase("test");
                          var collection = database.GetCollection<User>("test_collection");
                          User user = new User();
                          user.id = "1";
                          user.name = "mongo_test";
                          user.sex = "Female";
                          //Insert data user
                          collection.Insert(user);
                          // Get a data.
                          User result = collection.FindOne();
                          Console.WriteLine("id:" + result.id + " name:" + result.name + " sex:"+result.sex);
                          Console.WriteLine(“connection succeeded.........");
                      }
                      catch (Exception e)
                      {
                          Console.WriteLine(“connection Exceptional/Exception:"+
                      }
                  }
              }
              class User
              {
                  public string id { set; get; }
                  public string name { set; get; }
                  public string sex { set; get; }
          
              }
          }

          Go Linking Example

          Related link: MongoDB Go Driver.

          1. Install the following driver package.
          go get gopkg.in/mgo.v2

          If the download fails, advise you to set up a proxy:

          git config --global --unset http.proxy 
          git config --global --unset https.proxy

          2 . Obtain the cloud database MongoDB connection information.

          1. Go Demo Code.
          package main
          import (
          "fmt"
          "log"
          "time"
          "gopkg.in/mgo.v2"
          "gopkg.in/mgo.v2/bson"
          )
          type Person struct {
          Name  string
          Phone string
          }
          func main() {
          fmt.Println("hello world")
          dialInfo := &mgo.DialInfo{
          Addrs:     []string{"*********.mongodb.gz.baidubce.com:27017", "*********.mongodb.gz.baidubce.com:27017"},
          Direct:    false,
          Timeout:   time.Second * 1,
          Database:  "admin",
          Source:    "admin",
          Username:  "root",
          Password:  "*********",
          }
          session, err := mgo.DialWithInfo(dialInfo)
          if err != nil {
          fmt.Printf("dial failed: %v",err)
          return
          }
          defer session.Close()
          
          session.SetMode(mgo.Monotonic, true)
          
          c := session.DB("test").C("test_collection")
          err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
              &Person{"Cla", "+55 53 8402 8510"})
          if err != nil {
              log.Fatal(err)
          }
          
          result := Person{}
          err = c.Find(bson.M{"name": "Ale"}).One(&result)
          if err != nil {
              log.Fatal(err)
          }
          
          fmt.Println("Phone:", result.Phone)
          }
          Previous
          Connect to Sharded Cluster Instance Through MongoShell
          Next
          Data Backup