Mongo基于Java基本操作

1、使用Maven依赖相应jar

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>3.9.1</version>
</dependency>

2、获取客户端

  MongoClient mongoClient = MongoClients.create();// 获取本地默认端口的mongoDB服务

3、获取数据库

  MongoDatabase database = mongoClient.getDatabase("mongodb_test");

4、获取表

  MongoCollection coll = database.getCollection("member");

5、针对表的CRUD操作

  1)新增

    Document doc = new Document("name", "MongoDB")
      .append("type", "database")
      .append("count", 1)
      .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
      .append("info", new Document("x", 203).append("y", 102));
    coll.insertOne(doc);

 

  2)查询

 

    FindIterable<Document> results = coll.find();
    for (Document result : results) {
      System.out.println(result.getString("name"));
    }

 

  3)修改

 

    UpdateResult result = coll.updateMany(eq("name", "MongoDB Michael"), new Document("$set", new Document("name", "MongoDB")));
    System.out.println(result.getModifiedCount());

 

  4)删除

 

    DeleteResult result = coll.deleteMany(eq("type", "database"));
    System.out.println(result.getDeletedCount());

 

6、删除表

  coll.drop();

 

7、基于POJO的操作

  需要设置CodecRegistry,能够让对象与BSON互相转化

  比如:Member对象

 

@Data
public class Member {
private ObjectId id;
private String name;
private int age;
private String addr;
}

 

 

CodecProvider pojoCodecProvider = PojoCodecProvider.builder().register(Member.class).build();
CodecRegistry pojoCodecRegistry = fromRegistries(
fromCodecs(new StringCodec(),new IntegerCodec(),new ObjectIdCodec()) // 需要针对对象中的类型设置Codec
, fromProviders(pojoCodecProvider));

CodecRegistry
  
1)可以设置到MongoClient
    MongoClientSettings settings = MongoClientSettings.builder().codecRegistry(pojoCodecRegistry).build();
    MongoClient mongoClient = MongoClients.create(settings);

  2)可以设置到数据库
    database = database.withCodecRegistry(pojoCodecRegistry);
  3)可以设置到表
    collection = collection.withCodecRegistry(pojoCodecRegistry);

基于POJO的CRUD操作
1)新增
 
 Member member = new Member();
  member.setName("Michael");
  member.setAge(30);
  member.setAddr("SZ");

  coll.insertOne(member);

2)查询
  FindIterable<Member> results = coll.find();
  for (Member result : results) {
  System.out.println(result);
  }

3)修改
  UpdateResult result = coll.updateMany(eq("age",30),set("age",18));
  System.out.println(result);

4)删除数据
  DeleteResult result = coll.deleteMany(eq("name","Michael"));
  System.out.println(result);

5)删除表
  coll.drop();

 

posted @ 2018-12-30 12:01  生活咖啡  阅读(2357)  评论(0编辑  收藏  举报