数据库
首页 > 数据库> > 四、MongoDB原生Java客户端

四、MongoDB原生Java客户端

作者:互联网

MongoDB原生Java客户端

1.Maven依赖

<!-- mongodb -->
<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.5.0</version>
</dependency>

2.第一种方式:Document

2.1 连接MongoDB

// 数据库
private MongoDatabase db;

// 文档集合
private MongoCollection<Document> doc;

// 连接客户端(内置线程池)
private MongoClient client;

@Before
public void init() {
  client = new MongoClient("192.168.137.100", 27017);
  db = client.getDatabase("rab");
  doc = db.getCollection("users");
}

2.2 新增

@Test
public void insertDemo() {
  Document doc1 = new Document();

  doc1.append("username", "cang");
  doc1.append("country", "USA");
  doc1.append("age", 20);
  doc1.append("lenght", 1.77f);
  doc1.append("salary", new BigDecimal("6565.22"));// 存金额,使用bigdecimal这个数据类型

  Map<String, String> address1 = new HashMap<>();
  address1.put("aCode", "0000");
  address1.put("add", "xxx000");
  doc1.append("address", address1);

  // 添加“favorites”子文档,其中两个属性是数组
  Map<String, Object> favorites1 = new HashMap<String, Object>();
  favorites1.put("movies", Arrays.asList("aa", "bb"));
  favorites1.put("cites", Arrays.asList("东莞", "东京"));
  doc1.append("favorites", favorites1);

  Document doc2 = new Document();
  doc2.append("username", "Chen");
  doc2.append("country", "China");
  doc2.append("age", 30);
  doc2.append("lenght", 1.77f);
  doc2.append("salary", new BigDecimal("8888.22"));
  Map<String, String> address2 = new HashMap<>();
  address2.put("aCode", "411000");
  address2.put("add", "我的地址2");
  doc2.append("address", address2);
  Map<String, Object> favorites2 = new HashMap<>();
  favorites2.put("movies", Arrays.asList("东游记", "一路向东"));
  favorites2.put("cites", Arrays.asList("珠海", "东京"));
  doc2.append("favorites", favorites2);

  // 使用insertMany插入多条数据
  doc.insertMany(Arrays.asList(doc1, doc2));
}

2.3 查询

@Test
public void testFind() {
  final List<Document> ret = new ArrayList<>();
  // block接口专门用于处理查询出来的数据
  Block<Document> printBlock = new Block<Document>() {

    @Override
    public void apply(Document t) {
      logger.info(t.toJson());// 打印数据
      ret.add(t);
    }
  };
  // select * from users where favorites.cites has "东莞"、"东京"
  // db.users.find({ "favorites.cites" : { "$all" : [ "东莞" , "东京"]}})
  Bson all = all("favorites.cites", Arrays.asList("东莞", "东京"));

  FindIterable<Document> find = doc.find(all);

  find.forEach(printBlock);

  logger.info("------------------>" + String.valueOf(ret.size()));
  ret.removeAll(ret);

  // select * from users where username like '%s%' and (contry= English or contry
  // = USA)
  // db.users.find({ "$and" : [ { "username" : { "$regex" : ".*s.*"}} , { "$or" :
  // [ { "country" : "English"} , { "country" : "USA"}]}]})
  String regexStr = ".*s.*";

  Bson regex = regex("username", regexStr);// 定义数据过滤器,username like '%s%'

  Bson or = or(eq("country", "English"), eq("country", "USA"));// 定义数据过滤器,(contry= English or contry = USA)

  Bson and = and(regex, or);

  FindIterable<Document> find2 = doc.find(and);

  find2.forEach(printBlock);
  logger.info("------------------>" + String.valueOf(ret.size()));
}

2.4 修改

@Test
public void testUpdate() {
  // update users set age=6 where username = 'lison'
  // db.users.updateMany({ "username" : "lison"},{ "$set" : { "age" : 6}},true)
  Bson eq = eq("username", "lison"); // 定义数据过滤器,username = 'lison'

  Bson set = set("age", 8);// 更新的字段.来自于Updates包的静态导入

  UpdateResult updateMany = doc.updateMany(eq, set);

  logger.info("------------------>" + String.valueOf(updateMany.getModifiedCount()));// 打印受影响的行数

  // update users set favorites.movies add "小电影2 ", "小电影3" where favorites.cites
  // has "东莞"
  // db.users.updateMany({ "favorites.cites" : "东莞"}, { "$addToSet" : {
  // "favorites.movies" : { "$each" : [ "小电影2 " , "小电影3"]}}},true)
  Bson eq2 = eq("favorites.cites", "东莞");

  Bson addEachToSet = addEachToSet("favorites.movies", Arrays.asList("小电影2 ", "小电影3"));// 更新的字段.来自于Updates包的静态导入

  UpdateResult updateMany2 = doc.updateMany(eq2, addEachToSet);

  logger.info("------------------>" + String.valueOf(updateMany2.getModifiedCount()));

}

2.5 删除

@Test
public void testDelete() {
  // delete from users where username = ‘lison’
  Bson eq = eq("username", "lison"); // 定义数据过滤器,username='lison'
  DeleteResult deleteMany = doc.deleteMany(eq);

  logger.info("------------------>" + String.valueOf(deleteMany.getDeletedCount()));// 打印受影响的行数

  // delete from users where age >8 and age <25
  Bson gt = gt("age", 8);// 定义数据过滤器,age > 8,所有过滤器的定义来自于Filter这个包的静态方法,需要频繁使用所以静态导入
  // Bson gt = Filter.gt("age",8);
  Bson lt = lt("age", 25);// 定义数据过滤器,age < 25
  Bson and = and(gt, lt);// 定义数据过滤器,将条件用and拼接
  DeleteResult deleteMany2 = doc.deleteMany(and);
  logger.info("------------------>" + String.valueOf(deleteMany2.getDeletedCount()));// 打印受影响的行数
}

3.第二种方式:Pojo

3.1 连接MongoDB

private MongoDatabase db;

private MongoCollection<User> doc;

private MongoClient client;

@Before
public void init() {
  // 编解码器的list
  List<CodecRegistry> codecResgistes = new ArrayList<>();
  // list加入默认的编解码器集合
  codecResgistes.add(MongoClient.getDefaultCodecRegistry());
  // 生成一个pojo的编解码器
  CodecRegistry pojoCodecRegistry = CodecRegistries
      .fromProviders(PojoCodecProvider.builder().automatic(true).build());
  // list加入pojo的编解码器
  codecResgistes.add(pojoCodecRegistry);
  // 通过编解码器的list生成编解码器注册中心
  CodecRegistry registry = CodecRegistries.fromRegistries(codecResgistes);

  // 把编解码器注册中心放入MongoClientOptions
  // MongoClientOptions相当于连接池的配置信息
  MongoClientOptions build = MongoClientOptions.builder().codecRegistry(registry).build();

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

  client = new MongoClient(serverAddress, build);
  db = client.getDatabase("lison");
  doc = db.getCollection("users", User.class);
}

3.2 新增

@Test
public void insertDemo() {
  User user = new User();
  user.setUsername("cang");
  user.setCountry("USA");
  user.setAge(20);
  user.setLenght(1.77f);
  user.setSalary(new BigDecimal("6265.22"));

  // 添加“address”子文档
  Address address1 = new Address();
  address1.setaCode("411222");
  address1.setAdd("sdfsdf");
  user.setAddress(address1);

  // 添加“favorites”子文档,其中两个属性是数组
  Favorites favorites1 = new Favorites();
  favorites1.setCites(Arrays.asList("东莞", "东京"));
  favorites1.setMovies(Arrays.asList("西游记", "一路向西"));
  user.setFavorites(favorites1);

  User user1 = new User();
  user1.setUsername("chen");
  user1.setCountry("China");
  user1.setAge(30);
  user1.setLenght(1.77f);
  user1.setSalary(new BigDecimal("6885.22"));
  Address address2 = new Address();
  address2.setaCode("411000");
  address2.setAdd("我的地址2");
  user1.setAddress(address2);
  Favorites favorites2 = new Favorites();
  favorites2.setCites(Arrays.asList("珠海", "东京"));
  favorites2.setMovies(Arrays.asList("东游记", "一路向东"));
  user1.setFavorites(favorites2);

  // 使用insertMany插入多条数据
  doc.insertMany(Arrays.asList(user, user1));

}

3.3 查询

@Test
public void testFind() {

  final List<User> ret = new ArrayList<>();
  Block<User> printBlock = new Block<User>() {
    @Override
    public void apply(User t) {
      System.out.println(t.toString());
      ret.add(t);
    }

  };

  // select * from users where favorites.cites has "东莞"、"东京"

  Bson all = all("favorites.cites", Arrays.asList("东莞", "东京"));// 定义数据过滤器,喜欢的城市中要包含"东莞"、"东京"
  FindIterable<User> find = doc.find(all);
  find.forEach(printBlock);
  logger.info("------------------>" + String.valueOf(ret.size()));
  ret.removeAll(ret);

  // select * from users where username like '%s%' and (contry= English or contry
  // = USA)
  String regexStr = ".*s.*";
  Bson regex = regex("username", regexStr);// 定义数据过滤器,username like '%s%'
  Bson or = or(eq("country", "English"), eq("country", "USA"));// 定义数据过滤器,(contry= English or contry = USA)
  FindIterable<User> find2 = doc.find(and(regex, or));
  find2.forEach(printBlock);
  logger.info("------------------>" + String.valueOf(ret.size、()));

}

3.4 更新

@Test
public void testUpdate() {
  // update users set age=6 where username = 'lison'
  Bson eq = eq("username", "lison");// 定义数据过滤器,username = 'lison'
  Bson set = set("age", 8);// 更新的字段.来自于Updates包的静态导入
  UpdateResult updateMany = doc.updateMany(eq, set);
  logger.info("------------------>" + String.valueOf(updateMany.getModifiedCount()));// 打印受影响的行数

  // update users set favorites.movies add "小电影2 ", "小电影3" where favorites.cites
  // has "东莞"
  Bson eq2 = eq("favorites.cites", "东莞");// 定义数据过滤器,favorites.cites has "东莞"
  Bson addEachToSet = addEachToSet("favorites.movies", Arrays.asList("小电影2 ", "小电影3"));// 更新的字段.来自于Updates包的静态导入
  UpdateResult updateMany2 = doc.updateMany(eq2, addEachToSet);
  logger.info("------------------>" + String.valueOf(updateMany2.getModifiedCount()));
}

3.5 删除

@Test
public void testDelete() {

  // delete from users where username = ‘lison’
  Bson eq = eq("username", "lison");// 定义数据过滤器,username='lison'
  DeleteResult deleteMany = doc.deleteMany(eq);
  logger.info("------------------>" + String.valueOf(deleteMany.getDeletedCount()));// 打印受影响的行数

  // delete from users where age >8 and age <25
  Bson gt = gt("age", 8);// 定义数据过滤器,age > 8,所有过滤器的定义来自于Filter这个包的静态方法,需要频繁使用所以静态导入

  Bson lt = lt("age", 25);// 定义数据过滤器,age < 25
  Bson and = and(gt, lt);// 定义数据过滤器,将条件用and拼接
  DeleteResult deleteMany2 = doc.deleteMany(and);
  logger.info("------------------>" + String.valueOf(deleteMany2.getDeletedCount()));// 打印受影响的行数
}

标签:username,Java,users,MongoDB,favorites,new,Bson,eq,客户端
来源: https://blog.csdn.net/zcdlove/article/details/110451648