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"; // 多 IP 实例 Uri 可参考:mongodb://mongouser:******@172.xx.xx.124:27017,172.xx.xx.27:27017,172.xx.xx.136:27017/test?authSource=admin&replicaSet=cmgo-fsstfgob_0
MongoClientURI connStr = new MongoClientURI(mongoUri);
MongoClient mongoClient = new MongoClient(connStr);
try {
// 使用名为 someonedb 的数据库
MongoDatabase database = mongoClient.getDatabase("someonedb");
// 取得集合/表 someonetable 句柄
MongoCollection<Document> collection = database.getCollection("someonetable");
// 准备写入数据
Document doc = new Document();
doc.append("key", "value");
doc.append("username", "jack");
doc.append("age", 31);
// 写入数据
collection.insertOne(doc);
System.out.println("insert document: " + doc);
// 读取数据
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 {
//关闭连接
mongoClient.close();
}
}
}
本页内容是否解决了您的问题?