private ServerAddress serverAddress = new ServerAddress("101.132.251.198", 27017);
private MongoCredential credential = MongoCredential.createCredential("root", "tutorial", "root".toCharArray());
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoClientSettings settings = MongoClientSettings.builder()
.codecRegistry(pojoCodecRegistry)
.credential(credential)
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(serverAddress)))
.build();
MongoClient mongoClient = MongoClients.create(settings);
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import java.util.List;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;
import static java.util.Arrays.asList;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
@Data
@AllArgsConstructor
public final class Person {
private ObjectId id;
private String name;
private int age;
private Address address;
public Person() {
}
public Person(String name, int age, Address address) {
this.name = name;
this.age = age;
this.address = address;
}
}
@Data
@AllArgsConstructor
public final class Address {
private String street;
private String city;
private String zip;
public Address(){}
}
Creating a Custom CodecRegistry
PojoCodecProvider.builder()
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
Using the CodecRegistry
You can set it when instantiating a MongoClient object:
MongoClientSettings settings = MongoClientSettings.builder()
.codecRegistry(pojoCodecRegistry)
.credential(credential)
.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(serverAddress)))
.build();
MongoClient mongoClient = MongoClients.create(settings);
You can use an alternative CodecRegistry with a MongoDatabase:
database = database.withCodecRegistry(pojoCodecRegistry);
You can use an alternative CodecRegistry with a MongoCollection:
collection = collection.withCodecRegistry(pojoCodecRegistry);
Inserting a POJO into MongoDB
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);
<a name="ghxzq"></a>
### Insert Many Persons
```java
List<Person> people = Arrays.asList(
new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")),
new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")),
new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null))
);
collection.insertMany(people);
Query the Collection
@Test
public void testQuery() {
Block<Person> printBlock = new Block<Person>() {
@Override
public void apply(Person person) {
System.out.println(person);
}
};
collection.find().forEach(printBlock);
}
Specify a Query Filter
在查询Pojo时,您必须查询文档字段名称,而不是Pojo的属性名称。默认情况下它们是相同的,但是可以更改POJO属性名的映射方式。
Get A Single Person That Matches a Filter
Person somebody = collection.find(eq("address.city", "Wimborne")).first();
System.out.println(somebody);
Get All Person Instances That Match a Filter
collection.find(gt("age", 30)).forEach(printBlock);
Update Documents
Update a Single Person
collection.updateOne(eq("name", "Ada Byron"), Updates.combine(Updates.set("age", 23), Updates.set("name", "Ada Lovelace")));
collection.find(eq("name", "Ada Lovelace")).forEach(printBlock);
Update Multiple Persons
UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), Updates.set("zip", null));
System.out.println(updateResult.getModifiedCount());
Replace a Single Person
collection.replaceOne(eq("name", "Ada Lovelace"), ada);
Delete Documents
DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London"));
System.out.println(deleteResult.getDeletedCount());