1. 程式人生 > >Mongo基於Java基本操作

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();