<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.5.1</version>
</dependency>
</dependencies>
void testConnect() {
// MongoDB 连接 URI
String uri = "mongodb://demo:123456@192.168.1.15:27017/demo?maxPoolSize=20&w=majority";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// 获取 DataBase
MongoDatabase database = mongoClient.getDatabase("demo");
// 获取 Collection
MongoCollection<Document> order = database.getCollection("order");
// 执行查询
FindIterable<Document> documents = order.find();
for (Document next : documents) {
System.out.println(next.toString());
}
}
}
CodecRegistry 可以让对象与 BSON 自动转换
@Bean
public MongoClient mongoClient() {
String uri = "mongodb://demo:123456@192.168.1.15:27017/demo?maxPoolSize=20&w=majority";
// 创建 Codec 注册器
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
// 设置 true 实现自动映射
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())
);
MongoClientSettings se = MongoClientSettings.builder().codecRegistry(codecRegistry).applyConnectionString(new ConnectionString(uri)).build();
return MongoClients.create(se);
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
s 配置参数
spring:
data:
mongodb:
# 使用 uri
# uri: mongodb://user:pwd@ip1:port1,ip2:port2/database
uri: mongodb://demo:123456@192.168.1.15:27017/demo
# 使用多个参数配置
#host: 192.168.1.15
#port: 27017
#database: demo
#username: demo
#password: 123456
@Autowired
private MongoTemplate mongoTemplate;
MongoCollection<Document> getCollection(String collectionName)
<T> MongoCollection<T> getCollection(String collectionName, Class<T> documentClass)
void createCollection(String collectionName)
void createCollection(String collectionName, CreateCollectionOptions createCollectionOptions)
void drop()
MongoIterable<String> listCollectionNames()
ListCollectionsIterable<Document> listCollections()
命令执行
Document runCommand(Bson command)
void testInsert() {
MongoDatabase demo = mongoClient.getDatabase("demo");
Document document = new Document();
document.put("ping", 1);
Document result = demo.runCommand(document);
}
插入文档
insertMany(List<? extends T> documents)
insertOne(T document)
需要设置 CodecRegistry,能够让对象与 BSON 互相转化
// 报错
// org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class
// 需要 Codec
void testInsert() {
MongoCollection<Order> collection = mongoClient.getDatabase("demo").getCollection("order", Order.class);
Order order = new Order();
order.initValue();
InsertOneResult insertOneResult = collection.insertOne(order);
System.out.println(insertOneResult.wasAcknowledged());
}
/**************************************************** 改正后 ****************************************************/
void testInsert() {
// 创建 Codec 注册器
CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
// 设置 true 实现自动映射
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build())
);
// 根据 Codec 注册器获取 MongoCollection
MongoCollection<Order> collection = mongoClient.getDatabase("demo").getCollection("order", Order.class)
.withCodecRegistry(codecRegistry);
Order order = new Order();
order.initValue();
InsertOneResult insertOneResult = collection.insertOne(order);
System.out.println(insertOneResult.wasAcknowledged());
}
查询文档
更新文档
删除文档
插入文档
<T> T insert(T objectToSave, String collectionName)
<T> Collection<T> insertAll(Collection<? extends T> objectsToSave)
// 插入文档
void testInsert() {
Order order = new Order();
order.setName("Set Order Name");
mongoTemplate.insert(order, "order");
}
/******************** MongoDB 中的结果 ******************** /
{
"_id": {
"$oid": "626213847ad9c763dc4e94bc"
},
"name": "Set Order Name",
"_class": "com.example.mongo.model.Order"
}
查询文档
long count(Query query, String collectionName)
List<T> findAll(Class<T> entityClass, String collectionName)
List<T> find(Query query, Class<T> entityClass, String collectionName)
T findById(Object id, Class<T> entityClass, String collectionName)
T findOne(Query query, Class<T> entityClass, String collectionName)
Query with(Sort sort)
Query skip(long skip)
Query limit(int limit)
Criteria where(String key)
Criteria is(@Nullable Object value)
Criteria and(String key)
Criteria orOperator(Criteria... criteria)
Criteria orOperator(Collection<Criteria> criteria)
Criteria in(Object... values)
Criteria in(Collection<?> values)
Criteria ne(@Nullable Object value)
Criteria norOperator(Criteria... criteria)
Criteria norOperator(Collection<Criteria> criteria)
Criteria nin(Object... values)
Criteria nin(Collection<?> values)
Criteria gt(Object value)
Criteria gte(Object value)
Criteria lt(Object value)
Criteria lte(Object value)
Criteria regex(String regex)
void testFind() {
Criteria where = Criteria.where("name").is("Set Order Name");
Query query = new Query(where);
List<Order> orderList = mongoTemplate.find(query, Order.class, "order");
}
更新文档
UpdateResult updateFirst(Query query, UpdateDefinition update, String collectionName)
UpdateResult updateMulti(Query query, UpdateDefinition update, String collectionName)
Update set(String key, @Nullable Object value)
Update update(String key, @Nullable Object value)
Update inc(String key, Number inc)
Update pop(String key, Position pos)
Update pull(String key, @Nullable Object value)
Update pullAll(String key, Object[] values)
Update push(String key, @Nullable Object value)
Update addToSet(String key, @Nullable Object value)
void testUpdate() {
Criteria where = Criteria.where("name").is("Set Order Name");
Query query = new Query(where);
Update update = Update.update("name", "Update Oreder Name");
mongoTemplate.updateFirst(query, update, Order.class);
}
删除文档
DeleteResult remove(Query query, String collectionName)
T findAndRemove(Query query, Class<T> entityClass, String collectionName)
List<T> findAllAndRemove(Query query, Class<T> entityClass, String collectionName)
void testDelete() {
Criteria where = Criteria.where("name").is("Set Order Name");
Query query = new Query(where);
mongoTemplate.remove(query, "order");
}
分组查询
AggregationResults<T> aggregate(Aggregation aggregation, String collectionName, Class<T> outputType)
Aggregation newAggregation(List<? extends AggregationOperation> operations)
MatchOperation match(Criteria criteria)
ProjectionOperation project(String... fields)
Aggregation aggregation = Aggregation.project(Fields.fields("amount")).and("amount").multiply(100).as("amount"));
SortOperation sort(Sort sort)
GroupOperation group(String... fields)
SkipOperation skip(long elementsToSkip)
LimitOperation limit(long maxElements)
LookupOperation lookup(String from, String localField, String foreignField, String as)
UnwindOperation unwind(String field)
StartWithBuilder graphLookup(String fromCollection)
BucketOperation bucket(AggregationExpression groupByExpression)
FacetOperationBuilder facet(AggregationOperation... aggregationOperations)
void testInsert() {
//封装查询条件
List<AggregationOperation> operations = new ArrayList<>();
operations.add(Aggregation.group("null").sum("amount").as("amount"));
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<Order> order = mongoTemplate.aggregate(aggregation, "order", Order.class);
System.out.println(order.getMappedResults());
}
db.createUser(
{
"user": "<user_name>",
"pwd": "<password>",
"customData": {
# 任何描述用户信息的文档
"customDocument": "Custom Document"
},
"roles": [
{
role: "<role>",
db: "<database>"
},
"readWrite",
...
]
}
)
s 官方文档
MongoDB URI 格式
Java 驱动连接可选项
连接池
maxPoolSize
minPoolSize
maxIdleTimeMS
waitQueueTimeoutMS
复制集
replicaSet
事务
w
readPreference
spring:
data:
mongodb:
# 通过 URI 中的
# readPreference 配置读写分离
# slaveOk 配置从节点能读
uri: mongodb://user:password@ip_1:27017,ip_2:27017/demo?slaveOk=true&replicaSet=replicaName&write=1&readPreference=secondaryPreferred&connectTimeoutMS=300000