SpringBoot中MongoDB聚合管道查询操作$facet$lookup$unwind$group

前言、官方文档、MongoTemplate中的概念

前言

2023/3/14我是作者,原文最先发布在博客园(2022/12/09),今天把它复制以下到CSDN。 是的我是作者。

最近在做基于SpringBoot的MongoDB的聚合管道操作,JSON语句不难写,但是理清楚逻辑、顺序很麻烦,而且在Java(Springboot)上操作聚合管道,部分操作符的使用不清楚,加之网上可以参考的示例很零散,很多不够直观全面。

所以在翻阅了官方文档和一些个人分享的技术文章后,自己做了测试验证,汇总了这篇笔记,分享一下基于SpringBoot的MongoDB的聚合管道操作。

主要是聚焦于理解MongoDB Template提供的两种实现聚合管道的操作,重点基于$group,$lookup, $unwind, $facet, 这几个操作符,实际代码中也有涉及到$match, $count, $sortByCount的使用。

同时梳理一下MongoDB template中的几个定义(见“MongoTemplate中的概念”),希望有助于大家。

请大家配合标题导航食用,风味更佳~

可以转载,但请标注出处。

2023/3/7:补充,最近增加了一个数组字段的查询、更新操作详解笔记,如有需要可以点击这里跳转。

MongoDB数组查询、更新操作及$elemMatch、arrayFilter、占位符$、$push等操作符详解-CSDN博客

官方文档

$facet (aggregation) — MongoDB Manual

MongoTemplate相关概念

  • MongoTemplate:官方提供的操作MongoDB的对象。位于: org.springframework.data.mongodb.core。 使用的时候,需要注入。

  • Query:用于创建查询条件的对象。 位于:package org.springframework.data.mongodb.core.query。 使用时一般需要传入如"Criteria"构建的查询条件。

  • Criteria: 构建具体查询条件的对象,和Query位于同个包下。

  

  • AggregationOperation:聚合管道的操作对象,这是适用于Aggregate Pipeline Stages的操作,比如$group/$lookup/$unwind/$sort.......使用的时候,需要先构建对应的聚合操作,比如$group(需要构建具体操作), 可以创建多个,最后一并传入到Aggregation对象中,再交给template去执行管道聚合。 位于:

  • Aggregation:Pipeline stage的集合,也就是上面AggregationOperation的集合,把上面的所有聚合操作存在一起,template调用aggregate方法的时候,传入该对象。

  • 以上类位于 package org.springframework.data.mongodb.core.aggregation;

  • Aggregates: Pipeline stage操作对象。 和Aggregation有几乎一样的功能,但是会更加灵活,一般除了预先提供的操作符,还可以自己传入Bson操作对象去灵活实现。 整体的使用难度,比Aggregation可能高一些。

  • Bson、BsonDocument、BsonField: Bson我理解就是灵活的表达式,查询条件、聚合操作符之类的构建定义,都可以由它接收,并最后传给template的aggregate方法去执行聚合操作。BsonDocument则是Bson的具体实现,用于灵活构建表达式的对象。 关于这部分,具体可以往下看。BsonField也是构建灵活的聚合表达式的一个类,比如快速地定义{"count": { $sum: 1 } ,作为聚合操作的一部分传入到具体的聚合阶段中。

  • 以上类位于 package com.mongodb.client.model; Bson/BsonDocument则是另外的包中。org.bson中。感兴趣自行去源码中查找。

开发环境和参考文档

JDK1.8 + Maven

SpringBoot(Springboot-starter-parent): 2.7.5

Mongodb(spring-boot-starter-data-mongodb) 4.6.1

参考文档:

SpringBoot 集成 Spring Data Mongodb 操作 MongoDB 详解 | 小豆丁技术栈

Spring Boot MongoDB 查询操作 (BasicQuery ,BSON) | 数据库论坛

参考了以上网友的分享案例。

代码和案例

1. $count 和$match操作符

官方定义

$count: Passes a document to the next stage that contains a count of the number of documents input to the stage.

MongoDB数组查询、更新操作及$elemMatch、arrayFilter、占位符$、$push等操作符详解-CSDN博客

就是统计当前stage(聚合管道操作的阶段)存在的文档数量。

$match: Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.

过滤符合条件的数据到下个pipeline stage。

语法


{ $count: <string> // 这里的名称随便写,最后显示出来的结果就是 xxx : 总数 } 

// match语法
{ $match: { <query> } }  // 就是传入查询语句Json格式

在MongoDB中操作的官方示例


// 数据
{ "_id" : 1, "subject" : "History", "score" : 88 }
{ "_id" : 2, "subject" : "History", "score" : 92 }
{ "_id" : 3, "subject" : "History", "score" : 97 }
{ "_id" : 4, "subject" : "History", "score" : 71 }
{ "_id" : 5, "subject" : "History", "score" : 79 }
{ "_id" : 6, "subject" : "History", "score" : 83 }

// 执行

db.scores.aggregate(
// 先用match查找匹配的文档,然后直接用count统计当前match阶段存在的文档数量。
[{$match: {score: {$gt: 80}}},
{$count: "passing_scores" // 这里的passing_scores 也可以是其他任意名称
}]
)

// 返回结果
{ "passing_scores" : 4 }

MongoTemplate中实现的Java代码

数据参考上面官方示例。 以下分别是Aggregation和Aggregates的实现。 任意一种都可以。


    /**
     * @Author zaoyu
     */
    @Autowired
    private MongoTemplate mongoTemplate;

    private String DEMO_COLLECTION = "demo";


    /**
     * 用Aggregates和Bson构建聚合操作对象,用预先生成的MongoCollection对象调用aggregate执行即可。
     */
    @Test
    public void testCountWithAggregates(){
        MongoCollection<Document> collection = mongoTemplate.getCollection(DEMO_COLLECTION);
        // Aggregates提供各种操作符,返回一个Bson对象。这里用match,然后用Filters来实现过滤条件的构建,也是返回一个Bson对象。
        Bson matchBson = Aggregates.match(Filters.gt("score", 80));
        // 直接用Aggregates的count方法,如果不传自定义的名称,默认用“count”接收。
        Bson countBson = Aggregates.count("myCount");
        // 构建一个List<Bson>, 并把每一个聚合操作Bson加进去,最后传入aggregate方法中执行。
        List<Bson> bsonList = new ArrayList<>();
        bsonList.add(matchBson);
        bsonList.add(countBson);
        AggregateIterable<Document> resultList = collection.aggregate(bsonList);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }

    /**
     * @Author zaoyu
     * 用Aggregation集合接收聚合操作,用MongoTemplate对象直接调用aggregate,传入聚合操作集合、表名、映射对象。
     */
    @Test
    public void testCountWithAggregation(){
        // 构建查询match条件:分数大于80
        MatchOperation matchOperation = Aggregation.match(Criteria.where("score").gt(80));
        // 构建count操作,用“myCount”名称接收
        CountOperation countOperation = Aggregation.count().as("myCount");
        // 传入多个aggregation(聚合操作),用Aggregation对象接收。
        Aggregation aggregation = Aggregation.newAggregation(matchOperation, countOperation);
        // 直接用mongoTemplate调用aggregate方法,传入aggregation集合,表名,还有用什么对象接收数据,这里我用Document接收,不再建类。
        AggregationResults<Document> resultList = mongoTemplate.aggregate(aggregation, DEMO_COLLECTION, Document.class);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }
// 以上2个方法的输出结果一样,如下。
result is :Document{{myCount=4}}

2. $group 操作符

官方定义

The $group stage separates documents into groups according to a "group key". The output is one document for each unique group key. A group key is often a field, or group of fields. The group key can also be the result of an expression. Use the _id field in the $group pipeline stage to set the group key.

大概意思就是把文档做分组。 输出的格式是一条数据有一个唯一的分组键。 这里可以简单类比mysql 的group by分组。

语法


{
  $group:
    {
      _id: <expression>, // 用来分组的字段
      <field1>: { <accumulator1> : <expression1> }, // 对某字段做处理 accumulator操作。 
      ...
    }
 }

在MongoDB中操作的官方示例


// 插入数据
db.sales.insertMany([
  { "_id" : 1, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : NumberInt("2"), "date" : ISODate("2014-03-01T08:00:00Z") },
  { "_id" : 2, "item" : "jkl", "price" : NumberDecimal("20"), "quantity" : NumberInt("1"), "date" : ISODate("2014-03-01T09:00:00Z") },
  { "_id" : 3, "item" : "xyz", "price" : NumberDecimal("5"), "quantity" : NumberInt( "10"), "date" : ISODate("2014-03-15T09:00:00Z") },
  { "_id" : 4, "item" : "xyz", "price" : NumberDecimal("5"), "quantity" :  NumberInt("20") , "date" : ISODate("2014-04-04T11:21:39.736Z") },
  { "_id" : 5, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : NumberInt("10") , "date" : ISODate("2014-04-04T21:23:13.331Z") },
  { "_id" : 6, "item" : "def", "price" : NumberDecimal("7.5"), "quantity": NumberInt("5" ) , "date" : ISODate("2015-06-04T05:08:13Z") },
  { "_id" : 7, "item" : "def", "price" : NumberDecimal("7.5"), "quantity": NumberInt("10") , "date" : ISODate("2015-09-10T08:43:00Z") },
  { "_id" : 8, "item" : "abc", "price" : NumberDecimal("10"), "quantity" : NumberInt("5" ) , "date" : ISODate("2016-02-06T20:20:13Z") },
])

// 执行group,这里还加上了match 和 project和sort。 一并使用展示。


db.getCollection("sales").aggregate(
  // 第一个聚合管道:过滤出日期在2014-01-01到2015-01-01之间的数据
[ {
    $match : { "date": { $gte: new ISODate("2014-01-01"), $lt: new ISODate("2015-01-01") } }
  },
 // 第二个聚合管道:处理一下日期格式,方便等下做group。  
 {$project: 
     {quantity:1, 
         price:1,
         myDate:{"$dateToString":{format: "%Y-%m-%d", date: "$date"}}
 }},
 // 第三个聚合管道:分组统计,先按照日期分组,再统计每天的销售数量。        
 {$group:{_id:"$myDate", 
    perDayQuantity:{$sum:"$quantity"},
    myCount: {$sum:1}
   }},
 // 第四个聚合管道:按照每日销售数量降序排序
 {$sort:{"perDayQuantity":-1}}
])

MongoTemplate中实现的Java代码


  /**
   * @Author zaoyu
     * Aggregation 实现match, group, sort。
     */
    @Test
    public void testGroupAggregations(){
        // 第一阶段,过滤查询日期介于14-1-1~15-1-1之间的数据,用Aggregation实现类MatchOperation接收。
        MatchOperation match = Aggregation.match(Criteria
                .where("date").gte(Instant.parse("2014-01-01T08:00:00.000Z"))
                .andOperator(Criteria.where("date").lte(Instant.parse("2015-01-01T08:00:00.000Z"))));
        // 第二阶段,处理一下日期格式,方便等下做group,用ProjectionOperation接收,也是Aggregation的实现类。
        ProjectionOperation project = Aggregation.project("quantity", "price")
                .andExpression("{\"$dateToString\":{format: \"%Y-%m-%d\", date: \"$date\"}}").as("myDate");
        // 第三阶段,分组统计,先按照日期分组,再统计每天的销售数量。
        GroupOperation group = Aggregation.group("myDate")
                .sum("quantity").as("perDayQuantity")
                // 这里是计算文档条数
                .count().as("myCount");
        // 第四阶段,排序。按照perDayQuantity字段升序展示。
        SortOperation sort = Aggregation.sort(Sort.Direction.ASC, "perDayQuantity");
        // 用newAggregation接收以上多个阶段的管道聚合指令,执行,得到结果。
        Aggregation aggregations =Aggregation.newAggregation(match, project, group, sort);
        AggregationResults<Document> resultList = mongoTemplate.aggregate(aggregations, SALES_COLLECTION, Document.class);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }
// 返回结果
result is :Document{{_id=2014-03-01, perDayQuantity=3, myCount=2}}
result is :Document{{_id=2014-03-15, perDayQuantity=10, myCount=1}}
result is :Document{{_id=2014-04-04, perDayQuantity=30, myCount=2}}

3. $unwind 操作符

官方定义

Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.

大概意思就是把输入文档的数组字段按元素一个个拆分出来,并和原来的数据一并形成一条新文档输出。 好比原来10条数据,其中每条数据都有长度为3的数组,那么拆出来(在元素不重复的情况下),会得到30条数据。

语法


{ $unwind: <field path> }  

和

{
  $unwind:
    {
      path: <field path>,  // path是固定名称,沿用即可。 <field path> 是数组字段,就是你要拆分的字段(值得是一个数组,不然没有意义)
      includeArrayIndex: <string>,
      preserveNullAndEmptyArrays: <boolean>
    }
}

在MongoDB中操作的官方示例


// 插入数据
db.inventory.insertOne({ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] })

// 执行unwind操作,这里是把 sizes字段的数组拆分出来 
db.inventory.aggregate( [ { $unwind : "$sizes" } ] )

// 执行结果  可以看到每条数据的sizes不再是list,而是具体的元素。
{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }

注意,如果要拆分的字段是一个空数组或者null,那么实际输出的数据,不会包含那条数据。 如下示例。


// 插入多条数据,这里还放了三条特殊数据,一个是空集合,一个是null,一个是没有要拆分的字段 sizes
db.clothing.insertMany([
  { "_id" : 1, "item" : "Shirt", "sizes": [ "S", "M", "L"] },
  { "_id" : 2, "item" : "Shorts", "sizes" : [ ] },
  { "_id" : 3, "item" : "Hat", "sizes": "M" },
  { "_id" : 4, "item" : "Gloves" },
  { "_id" : 5, "item" : "Scarf", "sizes" : null }
])

// 执行$unwind
db.clothing.aggregate( [ { $unwind: { path: "$sizes" } } ] )

// 返回结果, 可以看到,sizes值为空数组和null的id=2以及id=5的数据都没有展示出来,同时没有该字段的id=4,也没有展示出来。
{ _id: 1, item: 'Shirt', sizes: 'S' },
{ _id: 1, item: 'Shirt', sizes: 'M' },
{ _id: 1, item: 'Shirt', sizes: 'L' },

MongoTemplate中实现的Java代码

以下分别是Aggregation和Aggregates的实现


  /**
     * @Author zaoyu
     * Aggregation 实现$unwind
     */
    @Test
    public void testUnwindAggregations() {
        String CLOTHING_COLLECTION = "clothing";
        // 调用Aggregation中的unwind的聚合操作符
        UnwindOperation unwind = Aggregation.unwind("sizes");
        // 用newAggregation接收管道聚合指令,执行,得到结果。
        Aggregation aggregations =Aggregation.newAggregation(unwind);
        // mongoTemplate 直接调用aggregate方法,传入Aggregation对象,基于的表,映射类(这里简单化,我用Document)
        AggregationResults<Document> resultList = mongoTemplate.aggregate(aggregations, CLOTHING_COLLECTION, Document.class);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }
    /**
     * @Author zaoyu
     * Aggregates/Bson 实现$unwind
     */
    @Test
    public void testUnwindAggregates(){
        String CLOTHING_COLLECTION = "clothing";
        // 调用Aggregates的unwind聚合操作符 注意,Aggregates这里需要传入$
        Bson unwindBson = Aggregates.unwind("$sizes");
        // 建一个List<Bson> 把unwindBson传进去
        List<Bson> bsonList = new ArrayList<>();
        bsonList.add(unwindBson);
        // mongoTemplate先获得对应的collection对象,然后调用aggregate,传入List<Bson> 获得结果
        MongoCollection<Document> collection = mongoTemplate.getCollection(CLOTHING_COLLECTION);
        AggregateIterable<Document> resultList = collection.aggregate(bsonList);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }

4. $lookup 操作符

官方定义

Performs a left outer join to a collection in the same database to filter in documents from the "joined" collection for processing. The $lookup stage adds a new array field to each input document. The new array field contains the matching documents from the "joined" collection.

The $lookup stage passes these reshaped documents to the next stage.

Starting in MongoDB 5.1, $lookup works across sharded collections.

其实可以简单理解类比Mysql的子查询。 会把另外一张表匹配的数据,作为一个数组存入到当前数据中,需要自定义一个字段来接收显示。

类比如下的sql语句


SELECT *, <output array field>
FROM collection
WHERE <output array field> IN (
   SELECT *
   FROM <collection to join>
   WHERE <foreignField> = <collection.localField>
);

【特别注意】如果当前DB是集群部署,那么在DB版本为5.1之前的情况,$lookup是不会生效的。 如果你数据库是集群的,然后又要用$lookup,一定要检查版本是否大于等于5.1,否则是查不出来的。 前阵子不知道这个,一直没有头绪为什么数据查不出来。

语法


{
   $lookup:
     {
       from: <collection to join>,  // 要联表查的表名
       localField: <field from the input documents>, // 当前表的要和联表关联的字段
       foreignField: <field from the documents of the "from" collection>, // 要被关联表的外键字段 
       as: <output array field> // 定义一个字段接收匹配关联的数据
     }
}

在MongoDB中操作的官方示例


// 插入表orders数据  
db.orders.insertMany( [
   { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
   { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
   { "_id" : 3  }
] )

// 插入表inventory数据
db.inventory.insertMany( [
   { "_id" : 1, "sku" : "almonds", "description": "product 1", "instock" : 120 },
   { "_id" : 2, "sku" : "bread", "description": "product 2", "instock" : 80 },
   { "_id" : 3, "sku" : "cashews", "description": "product 3", "instock" : 60 },
   { "_id" : 4, "sku" : "pecans", "description": "product 4", "instock" : 70 },
   { "_id" : 5, "sku": null, "description": "Incomplete" },
   { "_id" : 6 }
] )

执行代码


db.orders.aggregate( [ // db.orders 表示基于orders做聚合操作
   {
     $lookup:
       {
         from: "inventory",   // 联表inventory 
         localField: "item",  // 当前orders的字段
         foreignField: "sku", // inventory中的sku字段,和orders的item关联 
         as: "inventory_docs" // 定义一个字段名接收 inventory中sku 和orders的item相同的数据,数组形式。 
       }
  }
] )

返回结果


{
   "_id" : 1,
   "item" : "almonds",
   "price" : 12,
   "quantity" : 2,
   "inventory_docs" : [  // 这个inventory_docs字段就是自己命名的字段,存储着来自inventory的数据
      { "_id" : 1, "sku" : "almonds", "description" : "product 1", "instock" : 120 }
   ]
}
{
   "_id" : 2,
   "item" : "pecans",
   "price" : 20,
   "quantity" : 1,
   "inventory_docs" : [
      { "_id" : 4, "sku" : "pecans", "description" : "product 4", "instock" : 70 }
   ]
}
{
   "_id" : 3,
   "inventory_docs" : [
      { "_id" : 5, "sku" : null, "description" : "Incomplete" },
      { "_id" : 6 }
   ]
}

MongoTemplate中实现的Java代码

以下分别是Aggregation和Aggregates的实现


 /**
     * @Author zaoyu
     * Aggregation 实现$lookup
     */
    @Test
    public void testLookupAggregations(){
        String INVENTORY_COLLECTION = "inventory";
        String ORDERS_COLLECTION = "orders";
        // Aggregation类,直接可以调用lookup方法,传入要关联的表、当前表和关联表关联的字段、要关联的表的字段、自定义名称接收关联匹配的数据
        LookupOperation lookup = Aggregation.lookup(INVENTORY_COLLECTION, "item", "sku", "inventory_docs");
        // 用newAggregation接收管道聚合指令,执行,得到结果。
        Aggregation aggregations =Aggregation.newAggregation(lookup);
        // mongoTemplate 直接调用aggregate方法,传入Aggregation对象,基于的表,映射类(这里简单化,我用Document)
        AggregationResults<Document> resultList = mongoTemplate.aggregate(aggregations, ORDERS_COLLECTION, Document.class);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }

    /**
     * @Author zaoyu
     * Aggregates/Bson 实现$lookup
     */
    @Test
    public void testLookupAggregates(){
        String INVENTORY_COLLECTION = "inventory";
        String ORDERS_COLLECTION = "orders";
        // 这里用Aggregates类直接调用lookup,传入的参数和上面的Aggregations的lookup是一样的,只不过这里返回的结果是一个Bson对象。
        Bson lookupBson = Aggregates.lookup(INVENTORY_COLLECTION, "item", "sku", "inventory_docs");
        // 建一个List<Bson> 把lookupBson传进去
        List<Bson> bsonList = new ArrayList<>();
        bsonList.add(lookupBson);
        // mongoTemplate先获得对应的collection对象,然后调用aggregate,传入List<Bson> 获得结果
        MongoCollection<Document> collection = mongoTemplate.getCollection(ORDERS_COLLECTION);
        AggregateIterable<Document> resultList = collection.aggregate(bsonList);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }

返回结果


result is :Document{{_id=1.0, item=almonds, price=12.0, quantity=2.0, inventory_docs=[Document{{_id=1.0, sku=almonds, description=product 1, instock=120.0}}]}}
result is :Document{{_id=2.0, item=pecans, price=20.0, quantity=1.0, inventory_docs=[Document{{_id=4.0, sku=pecans, description=product 4, instock=70.0}}]}}
result is :Document{{_id=3.0, inventory_docs=[Document{{_id=5.0, sku=null, description=Incomplete}}, Document{{_id=6.0}}]}}

5. $facet 操作符

官方定义

Processes multiple aggregation pipelines within a single stage on the same set of input documents. Each sub-pipeline has its own field in the output document where its results are stored as an array of documents.

Input documents are passed to the $facet stage only once. $facet enables various aggregations on the same set of input documents, without needing to retrieve the input documents multiple times.

简单来说,就是facet可以实现在facet管道操作完成多个stage管道操作。减少获取输入文档的次数。

我个人觉得有种场景很适合使用facet:分页查询文档数据的同时,把符合查询条件的总数也查询出来的场景下,如果使用$facet,同时获取分页数据和总数,不用做两次数据库查询(分别查询分页数据和总数)。

语法


{ $facet:
   {
      <outputField1>: [ <stage1>, <stage2>, ... ],  // 这里outputpufield 是自己定义的用来接收stage集合返回的文档数据。  
      <outputField2>: [ <stage1>, <stage2>, ... ],  // 可以基于上一个Facet继续做facet
      ...
   }
}

在MongoDB中操作的官方示例


// 数据  插入artwork 表中 
{ "_id" : 1, "title" : "The Pillars of Society", "artist" : "Grosz", "year" : 1926,
  "price" : NumberDecimal("199.99"),
  "tags" : [ "painting", "satire", "Expressionism", "caricature" ] }
{ "_id" : 2, "title" : "Melancholy III", "artist" : "Munch", "year" : 1902,
  "price" : NumberDecimal("280.00"),
  "tags" : [ "woodcut", "Expressionism" ] }
{ "_id" : 3, "title" : "Dancer", "artist" : "Miro", "year" : 1925,
  "price" : NumberDecimal("76.04"),
  "tags" : [ "oil", "Surrealism", "painting" ] }
{ "_id" : 4, "title" : "The Great Wave off Kanagawa", "artist" : "Hokusai",
  "price" : NumberDecimal("167.30"),
  "tags" : [ "woodblock", "ukiyo-e" ] }
{ "_id" : 5, "title" : "The Persistence of Memory", "artist" : "Dali", "year" : 1931,
  "price" : NumberDecimal("483.00"),
  "tags" : [ "Surrealism", "painting", "oil" ] }
{ "_id" : 6, "title" : "Composition VII", "artist" : "Kandinsky", "year" : 1913,
  "price" : NumberDecimal("385.00"),
  "tags" : [ "oil", "painting", "abstract" ] }
{ "_id" : 7, "title" : "The Scream", "artist" : "Munch", "year" : 1893,
  "tags" : [ "Expressionism", "painting", "oil" ] }
{ "_id" : 8, "title" : "Blue Flower", "artist" : "O'Keefe", "year" : 1918,
  "price" : NumberDecimal("118.42"),
  "tags" : [ "abstract", "painting" ] }


// 执行$facet聚合
db.artwork.aggregate( [
  {
    $facet: {
        // 第一个Facet操作,按照tag分类:先用unwind拆分tags字段的数组值,交给下一个聚合 $sortByCount, 按照tags的个数排序。
      "categorizedByTags": [
        { $unwind: "$tags" },
        { $sortByCount: "$tags" }
      ],
    // 第二个Facet操作,按照price分类:先过滤数据(只处理存在price数据的文档),然后执行$bucket按照价格区间分组 0~150,151~200, 201~300, 301~400这样。
      "categorizedByPrice": [
        { $match: { price: { $exists: 1 } } },
        {
          $bucket: {
            groupBy: "$price",
            boundaries: [  0, 150, 200, 300, 400 ],
            default: "Other",
            output: {
              "count": { $sum: 1 },
              "titles": { $push: "$title" }
            }
          }
        }
      ],
// 第三个Facet, 按照years分类。 分成4个区间。
      "categorizedByYears(Auto)": [
        {
          $bucketAuto: {
            groupBy: "$year",
            buckets: 4
          }
        }
      ]
    }
  }
])

MongoTemplate中实现的Java代码

注:以下代码的实现,数据来源参考上边的官方示例的数据, artwork表。 请自行插入数据。

1. 使用Aggregation对象实现


 /**
     * @Author zaoyu
     * Aggregation 实现$facet
     */
    @Test
    public void testFacetAggregations(){
        String ARTWORK_COLLECTION = "artwork";
        // Facet中第一组分类(categorizedByTags)的两个聚合操作unwind 和 sortByCount
        UnwindOperation unwindForByTags = Aggregation.unwind("$tags");
        SortByCountOperation sortByCountForByTags = Aggregation.sortByCount("$tags");

        // Facet中第二组分类(categorizedByPrice)的聚合操作match 和 match
        MatchOperation matchForByPrice = Aggregation.match(Criteria.where("price").exists(true));
        // 分别传入bucket分组的字段price,设置区间值,并设置桶内条数统计和值(这里用titles接收title的值)
        BucketOperation bucketForByPrice = Aggregation.bucket("$price")
                .withBoundaries(0, 150, 200, 300, 400)
                .withDefaultBucket("Other")
                .andOutput("count").sum(1).as("count")
                .andOutput("$title").push().as("titles");

        // Facet中第三组分类 (categorizedByYears(Auto))的聚合操作,按年自动分成4个区间。
        BucketAutoOperation bucketForByYears = Aggregation.bucketAuto("$year", 4);

        // Aggregation调用facet方法,按照组别分类顺序,把每一组的聚合操作和输出的名称传进去。
        FacetOperation facetOperation = Aggregation.facet(unwindForByTags, sortByCountForByTags).as("categorizedByTags")
                .and(matchForByPrice, bucketForByPrice).as("categorizedByPrice")
                .and(bucketForByYears).as("categorizedByYears(Auto)");
        // 把facetOperation传入newAggregation得到Aggregation对象,调用mongoTemplate的Aggregate方法执行得到结果
        Aggregation aggregation = Aggregation.newAggregation(facetOperation);
        AggregationResults<Document> resultList = mongoTemplate.aggregate(aggregation, ARTWORK_COLLECTION, Document.class);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }

2. 使用Aggregates实现


/**
     * @Author zaoyu
     * Aggregates 实现$facet
     */
    @Test
    public void testFacetAggregates() {
        String ARTWORK_COLLECTION = "artwork";
        // Facet中第一组分类(categorizedByTags)的两个聚合操作unwind 和 sortByCount
        Bson unwindBsonForByTags = Aggregates.unwind("$tags");
        Bson sortByCountBsonForByTags = Aggregates.sortByCount("$tags");
        // 新建Facet对象,传入第一组分类的接收名称,以及在第一组分类中要做的聚合操作。
        Facet categorizedByTags = new Facet("categorizedByTags", unwindBsonForByTags, sortByCountBsonForByTags);

        // Facet中第二组分类(categorizedByPrice)的聚合操作match 和 match
        Bson matchBsonForPrice = Aggregates.match(Filters.exists("price"));
        // 这里面要新建BsonField构建 {"count": { $sum: 1 }  和 "titles": { $push: "$title" }} 作为第二组分类中$Bucket聚合操作中output值
        BsonField countOutput = new BsonField("count", new Document("$sum", 1));
        BsonField titleOutput = new BsonField("titles", new Document("$push", "$price"));
        // 上面2个操作传入到BucketOption对象,最后传到bucket操作
        BucketOptions bucketOptions = new BucketOptions().defaultBucket("Other").output(countOutput).output(titleOutput);
        Bson bucketBsonForByPrice = Aggregates.bucket("$price", Arrays.asList(0, 150, 200, 300, 400), bucketOptions);
        Facet categorizedByPrice = new Facet("categorizedByPrice", matchBsonForPrice, bucketBsonForByPrice);

        // Facet中第三组分类 (categorizedByYears(Auto))的聚合操作,按年自动分成4个区间。
        Bson bucketAutoBsonForByYears = Aggregates.bucketAuto("$year", 4);
        Facet categorizedByYears = new Facet("categorizedByYears", bucketAutoBsonForByYears);

        // 新建一个List<Facet>把每组分类的Facet对象传进去。
        List<Facet> facetList = new ArrayList<>();
        facetList.add(categorizedByTags);
        facetList.add(categorizedByPrice);
        facetList.add(categorizedByYears);
        // 调用Aggregates的facet方法,传入List<Facet>得到最终Bson对象,并添加到Bson集合中。
        Bson facetBson = Aggregates.facet(facetList);
        List<Bson> bsonList = new ArrayList<>();
        bsonList.add(facetBson);
        // 调用方法执行得到结果
        MongoCollection<Document> collection = mongoTemplate.getCollection(ARTWORK_COLLECTION);
        AggregateIterable<Document> resultList = collection.aggregate(bsonList);
        for (Document document : resultList) {
            System.out.println("result is :" + document);
        }
    }

最终返回结果, 二者一样。


result is :Document{{categorizedByTags=[Document{{_id=painting, count=6}}, Document{{_id=oil, count=4}}, 
Document{{_id=Expressionism, count=3}}, Document{{_id=Surrealism, count=2}}, 
Document{{_id=abstract, count=2}}, Document{{_id=woodblock, count=1}}, 
Document{{_id=ukiyo-e, count=1}}, Document{{_id=satire, count=1}}, 
Document{{_id=caricature, count=1}}, Document{{_id=woodcut, count=1}}
], 
categorizedByPrice=[Document{{_id=0, titles=[76.04, 118.42]}}, 
Document{{_id=150, titles=[199.99, 167.30]}}, 
Document{{_id=200, titles=[280.00]}}, 
Document{{_id=300, titles=[385.00]}}, 
Document{{_id=Other, titles=[483.00]}}], 
categorizedByYears=[Document{{_id=Document{{min=null, max=1902.0}}, count=2}}, 
Document{{_id=Document{{min=1902.0, max=1918.0}}, count=2}}, 
Document{{_id=Document{{min=1918.0, max=1926.0}}, count=2}}, 
Document{{_id=Document{{min=1926.0, max=1931.0}}, count=2}}]
}}
// 为方便好看,稍微调了下格式。

小结

整体来说,MonogoDB官方提供了很详细的资料,但对于Java 层面的操作,或者说SpringBoot层面的操作,文档就比较简单。

个人感觉而言,Aggregations提供的方法比较直接,更适合不太熟悉Springboot上操作Mongo的同学来使用,而Aggregates会更加灵活,但是需要你知道Document, BsonField, Bson之间的转换和获取。

有错漏之处,欢迎指正。

希望这篇文章能帮到你,如果有帮助到你,欢迎点赞评论关注打赏~~

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值