MongoDB Java Driver可以使Java能够操作MongoDB,从而进行增删改查等操作。
参考:
- http://www.runoob.com/mongodb/mongodb-java.html
- https://www.cnblogs.com/sa-dan/p/6836055.html
- http://mongodb.github.io/mongo-java-driver/3.10/javadoc/overview-summary.html
- http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/
- https://www.cnblogs.com/sa-dan/p/6836055.html
需要先安装mongo-java-driver:http://central.maven.org/maven2/org/mongodb/mongo-java-driver/
或者:https://mongodb.github.io/mongo-java-driver/
将此包导入到项目中即可使用。
基本操作
连接服务:
MongoClient mongoClient = new MongoClient(host, port);
连接数据库:
MongoDatabase mongoDatabase = mongoClient.getDatabase("dbName");
获取集合:
MongoCollection<Document> collection = mongoDatabase.getCollection("cltName");
创建集合:
mongoDatabase.createCollection("cltName");
创建文档:需要导入org.bson.Document
Document document = new Document("key", value).
append("key", value).
append("key", value);
创建文档集:需要导入java.util.List
List<Document> documents = new ArrayList<Document>(); // 创建文档集
documents.add(document); // 添加文档
向集合插入文档集:
collection.insertMany(documents);
删除文档:需要设置条件,然后才能删除满足条件的文档
collection.deleteOne(Filters.eq("key", val)); // 删除第一条
collection.deleteMany(Filters.eq("key", val)); // 删除所有
修改文档:同样需要设置条件,然后才能修改满足条件的文档
// 修改满足条件的第一条文档
collection.updateOne();
// 修改满足条件的所有文档
collection.updateMany(Filters.eq("key", value), new Document("$set",new Document("newKey",newValue)));
查询文档:
Document myDoc = collection.find(Filters.eq("key", value)).first(); // 获得集合中第一条数据
检索文档:通过游标遍历整个集合
FindIterable<Document> findIterable = collection.find(); // 迭代器
MongoCursor<Document> mongoCursor = findIterable.iterator(); // 游标
while(mongoCursor.hasNext()){ // 遍历游标
System.out.println(mongoCursor.next());
}