Updated on 2024-02-07 GMT+08:00

Complete Example

package mongodbdemo;
import org.bson.*;
import com.mongodb.*;
import com.mongodb.client.*;
public class MongodbDemo {
    public static void main(String[] args) {
       // There will be security risks if the username and password used for authentication are directly written into code. Store the username and password in ciphertext in the configuration file or environment variables.
       // In this example, the username and password are stored in the environment variables. Before running this example, set environment variables EXAMPLE_USERNAME_ENV and EXAMPLE_PASSWORD_ENV as needed.
       String userName = System.getenv("EXAMPLE_USERNAME_ENV");
       String rwuserPassword = System.getenv("EXAMPLE_PASSWORD_ENV");
       String mongoUri = "mongodb://" + userName + ":" + rwuserPassword + "@10.66.187.127:27017/admin";
       MongoClientURI connStr = new MongoClientURI(mongoUri);
       MongoClient mongoClient = new MongoClient(connStr);
       try {
           //Use the database named someonedb.
           MongoDatabase database = mongoClient.getDatabase("someonedb");
           //Obtain the someonetable handle of the collection/table.
           MongoCollection<Document> collection = database.getCollection("someonetable");
            //Prepare data to be written.
           Document doc = new Document();
           doc.append("key", "value");
           doc.append("username", "jack");
           doc.append("age", 31);
            //Write data.
           collection.insertOne(doc);
           System.out.println("insert document: " + doc);
            //Read data.
           BsonDocument filter = new BsonDocument();
           filter.append("username", new BsonString("jack"));
           MongoCursor<Document> cursor = collection.find(filter).iterator();
           while (cursor.hasNext()) {
               System.out.println("find document: " + cursor.next());
           }
       } finally {
           //Close the connection.
           mongoClient.close();
       }
   }
}

For more information about Java APIs, see the official documents.