Java操作MongoDB3.2概述
2016-09-07 13:23
459 查看
MongoDB3.2的Java驱动基本推翻了之前2.x版本的用法,其使用方法有了很大的不同。本文整理了Java如何在有auth和无auth认证下连接MongoDB3.2以及一些基本的增删改查的操作。
插入操作
查询操作
修改操作
删除操作
更多MongoDB操作请参考官方文档。
Java连接有auth认证
MongoClient client = null; ServerAddress serverAddress = new ServerAddress("localhost", 27017); List<ServerAddress> seeds = new ArrayList<ServerAddress>(); seeds.add(serverAddress); MongoCredential credentials= MongoCredential.createScramSha1Credential("gleradmin", "admin","gleradmin".toCharArray()); List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); credentialsList.add(credentials); client = new MongoClient(seeds, credentialsList); MongoDatabase db = client.getDatabase("testcol"); MongoCollection<Document> collection = db.getCollection("userinfo");
Java连接无有auth认证
MongoClient mongoClient = new MongoClient("192.168.0.102", 20000); MongoDatabase db = mongoClient.getDatabase("testcol"); MongoCollection<Document> collection = db.getCollection("userinfo");
插入操作
//批量插入多个文档 List<Document> list = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { Document document = new Document(); document.put("username", "user" + (i + 1)); document.put("password", "123456"); document.put("name", "user" + (i + 1)); document.put("sex", "man"); list.add(document); } collection.insertMany(list);
查询操作
//全表扫描 MongoCursor<Document> cursor = collection.find().iterator(); while(cursor.hasNext()){ //cursor.next(); System.out.println(cursor.next()); } //模糊查询,字段"username"包含"11"的文档 Pattern pattern = Pattern.compile("^.*11.*$", Pattern.CASE_INSENSITIVE); BasicDBObject query = new BasicDBObject(); query.put("username",pattern); FindIterable<Document> findIterable = collection.find(query); MongoCursor<Document> cursor = findIterable.iterator(); while (cursor.hasNext()) { //cursor.next(); System.out.println(cursor.next()); }
修改操作
//将文档的字段"username"为"user1"修改为"Tom" collection.findOneAndReplace(new Document("username","user1"), new Document("username","Tom"));
删除操作
//删除所有文档(删除一个用deleteOne()方法) collection.deleteMany(new Document()); //删除"sex"字段问"man"的所以文档 collection.deleteMany(Filters.all("sex", "man"));
更多MongoDB操作请参考官方文档。
相关文章推荐
- MongoDB在java中的操作-添,删,查 基本数据 文件存储 可使用
- MongoDB下的查询操作(与上篇文章java api查询操作对应)
- apache POI3.2 java操作excel 设置数据有效性,实现excel单元格列表和提示
- JAVA操作mongoDB(一) helloworld
- Mongodb快速入门之使用Java操作Mongodb
- apache POI3.2 java操作excel 设置数据有效性,实现excel单元格列表和提示
- Java操作MongoDB
- 【MongoDB for Java】Java操作MongoDB
- Java操作MongoDB
- MongoDB——Java操作(增删改查)
- 【MongoDB for Java】Java操作MongoDB
- MongoDB,java操作
- Java实现对MongoDB的AND、OR和IN操作
- 【MongoDB for Java】Java操作MongoDB
- 如何用Java操作MongoDB(1)
- mongoDB JAVA操作
- Java Tutorial(Java操作MongoDB入门)
- Mongodb快速入门之使用Java操作Mongodb
- java操作MongoDB存储文件
- Java操作Mongodb