Updated on 2022-09-21 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) {
       String mongoUri = "mongodb://mongouser:thepasswordA1@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.