1. private ServerAddress serverAddress = new ServerAddress("101.132.251.198", 27017);
  2. private MongoCredential credential = MongoCredential.createCredential("root", "tutorial", "root".toCharArray());
  3. CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
  4. fromProviders(PojoCodecProvider.builder().automatic(true).build()));
  5. MongoClientSettings settings = MongoClientSettings.builder()
  6. .codecRegistry(pojoCodecRegistry)
  7. .credential(credential)
  8. .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(serverAddress)))
  9. .build();
  10. MongoClient mongoClient = MongoClients.create(settings);
  1. import com.mongodb.Block;
  2. import com.mongodb.MongoClient;
  3. import com.mongodb.MongoClientURI;
  4. import com.mongodb.client.MongoCollection;
  5. import com.mongodb.client.MongoDatabase;
  6. import com.mongodb.client.result.DeleteResult;
  7. import com.mongodb.client.result.UpdateResult;
  8. import org.bson.codecs.configuration.CodecRegistry;
  9. import org.bson.codecs.pojo.PojoCodecProvider;
  10. import java.util.List;
  11. import static com.mongodb.client.model.Filters.*;
  12. import static com.mongodb.client.model.Updates.*;
  13. import static java.util.Arrays.asList;
  14. import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
  15. import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
  1. @Data
  2. @AllArgsConstructor
  3. public final class Person {
  4. private ObjectId id;
  5. private String name;
  6. private int age;
  7. private Address address;
  8. public Person() {
  9. }
  10. public Person(String name, int age, Address address) {
  11. this.name = name;
  12. this.age = age;
  13. this.address = address;
  14. }
  15. }
  16. @Data
  17. @AllArgsConstructor
  18. public final class Address {
  19. private String street;
  20. private String city;
  21. private String zip;
  22. public Address(){}
  23. }

Creating a Custom CodecRegistry

  • PojoCodecProvider.builder()

    1. CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
    2. fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    Using the CodecRegistry

  • You can set it when instantiating a MongoClient object:

    1. MongoClientSettings settings = MongoClientSettings.builder()
    2. .codecRegistry(pojoCodecRegistry)
    3. .credential(credential)
    4. .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(serverAddress)))
    5. .build();
    6. MongoClient mongoClient = MongoClients.create(settings);
  • You can use an alternative CodecRegistry with a MongoDatabase:

    1. database = database.withCodecRegistry(pojoCodecRegistry);
  • You can use an alternative CodecRegistry with a MongoCollection:

    1. collection = collection.withCodecRegistry(pojoCodecRegistry);

    Inserting a POJO into MongoDB

    1. MongoCollection<Person> collection = database.getCollection("people", Person.class);

    Insert a Person

    ```java Person ada = new Person(“Ada Byron”, 20, new Address(“St James Square”, “London”, “W1”));

collection.insertOne(ada);

  1. <a name="ghxzq"></a>
  2. ### Insert Many Persons
  3. ```java
  4. List<Person> people = Arrays.asList(
  5. new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")),
  6. new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")),
  7. new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null))
  8. );
  9. collection.insertMany(people);

Query the Collection

  1. @Test
  2. public void testQuery() {
  3. Block<Person> printBlock = new Block<Person>() {
  4. @Override
  5. public void apply(Person person) {
  6. System.out.println(person);
  7. }
  8. };
  9. collection.find().forEach(printBlock);
  10. }

image.png

Specify a Query Filter

在查询Pojo时,您必须查询文档字段名称,而不是Pojo的属性名称。默认情况下它们是相同的,但是可以更改POJO属性名的映射方式。

Get A Single Person That Matches a Filter

  1. Person somebody = collection.find(eq("address.city", "Wimborne")).first();
  2. System.out.println(somebody);

image.png

Get All Person Instances That Match a Filter

  1. collection.find(gt("age", 30)).forEach(printBlock);

Update Documents

Update a Single Person

  1. collection.updateOne(eq("name", "Ada Byron"), Updates.combine(Updates.set("age", 23), Updates.set("name", "Ada Lovelace")));
  2. collection.find(eq("name", "Ada Lovelace")).forEach(printBlock);

image.png

Update Multiple Persons

  1. UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), Updates.set("zip", null));
  2. System.out.println(updateResult.getModifiedCount());

Replace a Single Person

  1. collection.replaceOne(eq("name", "Ada Lovelace"), ada);

Delete Documents

  1. DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London"));
  2. System.out.println(deleteResult.getDeletedCount());