Java实现对MongoDB的增删改查

一、连接数据库

连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。

连接数据库的Java代码如下(无需密码的连接)

 public class MongTest {

  public static void main(String[] args) {

          try {

              MongoClient mongoClient = new MongoClient("localhost",27017);//连接到 mongodb 服务

           MongoDatabase mongoDatabase= mongoClient.getDatabase("mymong");//连接到数据库

           System.out.println("连接成功");

      } catch (Exception e) {

           System.err.println(e.getClass().getName()+":"+e.getMessage());

      }

   }

}

如果Mongo 需要验证用户名及密码,可以使用以下代码

public class MongoDBJDBC { 

    public static void main(String[] args){ 

        try { 

            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址 

            //ServerAddress()两个参数分别为服务器地址和端口 

            ServerAddress serverAddress = new ServerAddress("localhost",27017); 

            List addrs = new ArrayList(); 

            addrs.add(serverAddress); 

              

            //MongoCredential.createScramSha1Credential()三个参数分别为用户名数据库名称密码 

            MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray()); 

            Listcredentials = new ArrayList(); 

            credentials.add(credential); 

             

            //通过连接认证获取MongoDB连接 

            MongoClient mongoClient = new MongoClient(addrs,credentials); 

             

            //连接到数据库 

            MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName"); 

            System.out.println("Connect to database successfully"); 

        } catch (Exception e) { 

            System.err.println( e.getClass().getName() + ": " + e.getMessage() ); 

        } 

    } 

}

二、创建集合

使用 com.mongodb.client.MongoDatabase 类中的createCollection()来创建集合:

mongoDatabase.createCollection("test");//创建集合test

System.out.println("创建集合成功!");

 

三、获取集合

使用com.mongodb.client.MongoDatabase类的getCollection() 方法来获取一个集合 :

MongoCollection collection = mongoDatabase.getCollection("test");

           System.out.println("集合选择成功!");

 

四、插入文档

使用com.mongodb.client.MongoCollection类的insertMany() 方法来插入一个文档 :

Document document = new Document("title","UserInfo");

document.append("Name", "张三");

document.append("Age", 30);

document.append("Addr", "西安"); 

List documents = newArrayList(); 

documents.add(document); 

collection.insertMany(documents); 

System.out.println("文档插入成功");         

五、检索所有文档

使用 com.mongodb.client.MongoCollection 类中的find() 方法来获取集合中的所有文档。此方法返回一个游标,所以需要遍历这个游标:

FindIterable findIterable= collection.find();

MongoCursor mongoCursor = findIterable.iterator();

while(mongoCursor.hasNext()){

System.out.println(mongoCursor.next());

           }

 

 

将文档信息封装成对象:

List userList = newArrayList();

User user =null;

while(mongoCursor.hasNext()){

    user = newUser();

 user.setName(mongoCursor.next().getString("Name"));

    user.setAge(mongoCursor.next().getInteger("Age"));

user.setAddr(mongoCursor.next().getString("Addr"))        

userList.add(user);

           }

           

          for(User u:userList){

             System.out.println(u);

           }

User类的定义:

public classUser {

  private String name;

  private Integer age;

  private String addr;

//省去set/get方法

   @Override

  public String toString() {

     return "User [name="+ name+ ", age="+ age+ ", addr="+ addr+ "]";

   }

}

六、更新文档

使用 com.mongodb.client.MongoCollection 类中的updateMany() 方法来更新集合中的文档。

//更新文档   将文档中Age=30的文档修改为Age=50   
         collection.updateMany(Filters.eq("Age",30), new Document("$set",new Document("Age",50)));  
         //检索查看结果  
         FindIterable<</span>Document> findIterable = collection.find();  
         MongoCursor<</span>Document> mongoCursor = findIterable.iterator();  
         while(mongoCursor.hasNext()){  
            System.out.println(mongoCursor.next());  
         }  

七、删除第一个文档

要删除集合中的第一个文档,首先需要使用com.mongodb.DBCollection类中的 findOne()方法来获取第一个文档,然后使用remove 方法删除。

 

//删除符合条件的第一个文档  
         collection.deleteOne(Filters.eq("Age",30));  
         //删除所有符合条件的文档  
         collection.deleteMany (Filters.eq("Age",30));

猜你喜欢

转载自www.cnblogs.com/lone5wolf/p/10856039.html