Help Center/ Document Database Service/ Developer Guide/ Application Development/ Java-based Development/ Complete Example
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.
Parent topic: Java-based Development
What is your overall rating for this page?
0
1
2
3
4
5
6
7
8
9
10
Very dissatisfiedVery satisfied
Thank you very much for your feedback. We will continue working to improve the documentation.
The system is busy. Please try again later.