Java操作MongoDB3.2概述

MongoDB3.2的Java驱动基本推翻了之前2.x版本的用法,其使用方法有了很大的不同。本文整理了Java如何在有auth和无auth认证下连接MongoDB3.2以及一些基本的增删改查的操作。


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操作请参考官方文档。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值