运行环境:
java1.8
mongodb3.0
mongo-java-driver3.7.0
获取数据库
MongoClient client = MongoClients.create("mongodb://localhost:27017");
MongoDatabase db = client.getDatabase("test");
创建集合
MongoCollection<Document> mycol = db.createCollection("mycol");
获取集合
MongoCollection<Document> mycol = db.getCollection("mycol");
删除集合
db.getCollection("mycol").drop;
查看集合中所有文档
FindIterable<Document> iterator = db.getCollection("mycol").find();
MongoCursor<Document> iterator = iterator.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
获取集合中文档的个数
long count = db.getCollection("mycol").count();
插入一个文档
mycol.insertOne(new Document("title", 1234));
插入多个文档
Document doc1 = new Document("title", "title1");
Document doc2 = new Document("title", "title2");
List<Document> docs = new ArrayList<Document>();
docs.add(doc1);
docs.add(doc2);
mycol.insertMany(docs);
更新文档
Document doc = new Document("title", "title1");
Bson filter = Filters.eq("title", "title1");
Bson update = new Document("$set", new Document("title", "title2"));
mycol.updateMany(filter, update);
删除一个文档
Bson filter = Filters.eq("title", "title1");
mycol.deleteOne(filter);
删除多个文档
Bson filter = Filters.eq("title", "title2");
mycol.deleteMany(filter);
关闭连接
client.close();