# Using MongoDB in Spring

# 参考文档

# 引入

  1. 引入依赖

    <!-- mongodb -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    
    1
    2
    3
    4
    5
  2. 配置连接信息

    spring:
        data:
            mongodb:
            # uri: mongodb://admin:123456@127.0.0.1:27017/admin
                host: 127.0.0.1
                port: 27017
                database: test
                username: admin
                password: 123456
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
  3. 使用 MongoTemplate

# Aggregate

Mongo Shell:

db.orders.aggregate(
    [
        // $match 指定 query 条件
        { $match: { status: "A" } },
        // _id 指定按照哪个字段去分组
        { $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
        // 多字段分组时需要设置一个别名
        // { $group: { _id: { "custId": "$cust_id", "bId": "$b_id"}, total: { $sum: "$amount" } } },
        { $sort: { total: -1 } }
    ],
    {
        explain: true,
        // 使用外部排序执行大型排序操作
        allowDiskUse: true,
        // 指定初始批量大小
        cursor: { batchSize: 0 },
        // 指定索引
        hint: { qty: 1, category: 1 }
    }
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

对应 Java API:

// ...
import org.springframework.data.mongodb.core.aggregation.Aggregation;

MatchOperation matchStage = Aggregation.match(Criteria.where("status").is("A"));
GroupOperation groupStage = Aggregation.group("cust_id").sum("amount").as("total");
// GroupOperation groupStage = Aggregation.group("cust_id", "bid").sum("amount").as("total");
AggregationOptions aggregateOptions = AggregationOptions.builder()
    .explain(true)
    .allowDiskUse(true)
    .cursorBatchSize(20)
    .hint(Document.parse("{ qty: 1, category: 1 }"))
    .build();
mongoTemplate.aggregate(
    Aggregation.newAggregation(matchStage, groupStage).withOptions(aggregateOptions),
    "collectionName",
    Result.class
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 问题

Spring 操作 MongoDB 分页从 0 开始。

// page 从 0 开始,而不是 1
PageRequest.of(page, size)
1
2

# 讨论区

由于评论过多会影响页面最下方的导航,故将评论区做默认折叠处理。

点击查看评论区内容,渴望您的宝贵建议~
Last Updated: 5/4/2023, 6:48:38 PM