MongoDB和Java-PHP

一、java操作mongoDB

配置环境:

1、下mongodb JDBC驱动mongo-java-driver-3.2.2.jar,并包含在classpath中

步骤:

1、连接数据库

1 // 连接到 mongodb 服务
2 MongoClient mongoClient = new MongoClient( "localhost" , 27017 );      
3 // 连接到数据库
4 MongoDatabase mongoDatabase =mongoClient.getDatabase("mycol");

 

2、如果需要验证用户名和密码,则

 1 //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址  
 2 //ServerAddress()两个参数分别为 服务器地址 和 端口  
 3 ServerAddress serverAddress = new ServerAddress("localhost",27017);  
 4 List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
 5 addrs.add(serverAddress);                
 6 //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码  
 7 MongoCredential credential =MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());  
 8 List<MongoCredential> credentials = new ArrayList<MongoCredential>();  credentials.add(credential);  
 9 //通过连接认证获取MongoDB连接  
10 MongoClient mongoClient = new MongoClient(addrs,credentials);  
11 //连接到数据库  
12 MongoDatabase mongoDatabase =mongoClient.getDatabase("databaseName"); 

3、操作数据库

创建集合

 mongoDatabase.createCollection("test");

获取集合

 MongoCollection<Document> collection = mongoDatabase.getCollection("test");

插入文档

1 Document document = new Document("title", "MongoDB").  
2 append("description", "database").  
3 append("likes", 100).  
4 append("by", "Fly");  
5 List<Document> documents = new ArrayList<Document>();  
6 documents.add(document);  
7 collection.insertMany(documents); 

获取文档

1 FindIterable<Document> findIterable = collection.find();  //获取迭代器
2 MongoCursor<Document> mongoCursor = findIterable.iterator();  //获取游标
3 while(mongoCursor.hasNext()){  
4        System.out.println(mongoCursor.next());  
5 }  

更新文档

1 //更新文档   将文档中likes=100的文档修改为likes=200   
2 collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));  

删除文档

1 //删除符合条件的第一个文档  
2 collection.deleteOne(Filters.eq("likes", 200));  
3 //删除所有符合条件的文档  
4 collection.deleteMany (Filters.eq("likes", 200));  

 

posted @ 2016-05-01 21:33  impwang  阅读(282)  评论(0编辑  收藏  举报