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

三、mongdb 查询 基于上一章,主要讲解mongodb的常用语法,下一章节主要讲解springboot进行连接mongodb 阅读详情

前言、官方文档、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之间的转换和获取。

有错漏之处,欢迎指正。

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

​

springboot 和mongo 聚合多个参数及分页排序和创建索引 我们在使用mongodb有时候需要 group by 参数1,参数2,并在分组中进行排序分页操作。这里我将这种例子展示出来,大家可以作为参考。如果需要查看mongo和springboot结合的配置可以参考,下面这两篇文章。 https://blog.csdn.net/fajing_feiyue/article/details/103330764 https://blog.csdn.net/faj... 阅读详情

相关推荐

Spring Boot中使用MongoDB聚合管道进行数据查询操作

在上面的代码中,我们使用Aggregation类创建了一个聚合管道查询,并使用$facet操作符进行分组。在上面的代码中,我们使用Aggregation类创建了一个聚合管道查询,并使用$lookup操作符将User集合中的"departmentId"字段与Department集合中的"_id"字段进行关联查询。在上面的代码中,我们使用Aggregation类创建了一个聚合管道查询,并使用$group操作符按照"age"字段进行分组,并使用count操作符计算每个年龄组的文档数量。操作符进行分组操作。

BitCodeW的博客 369

MongoDB聚合操作符$facet的使用及案例

facet 是 MongoDB 中的一个聚合操作符,它允许在单个聚合阶段中并行执行多个子聚合操作。每个 $facet 阶段都可以包含多个子阶段,这些子阶段可以独立地对输入文档集进行处理。下面是一个使用案例,包括插入和测试数据。首先,让我们考虑一个假设的场景:假设我们有一个名为 “orders” 的集合,其中存储了客户订单的信息。每个订单文档包含了客户 ID、订单日期、订单总额等字段。

new_Learn0822的博客 1225

SAP入门技术分享四:模块化程序

SAP入门技术分享三:模块化程序

ITxiaoangzai的博客 1158

MongoDB聚合:$facet

对输入的文档执行多个聚合管道,在输出结果中,每个子管道一个字段,字段值是一个文档数组。$facet可以在一个阶段创建多面聚合,横跨多个维度或方面来描述数据特征。多面聚合可提供多个过滤器和分类指导数据浏览和分析。$facet阶段在单个聚合阶段内创建多面聚合,通过多个维度或面来描述数据特征。多面聚合提供了多个过滤器和分类,为数据浏览和分析导航,零售商通常通过创建产品价格、制造商、尺寸等方面的过滤器以及使用分面来缩小搜索范围。

superatom01的博客 1277

手把手教你用Ubuntu Desktop搭建个人L2TP服务器,手机电脑都能连(Network Manager配置详解)

本文详细介绍了在Ubuntu Desktop上使用Network Manager图形化配置L2TP服务器的方法,实现手机、电脑等多设备安全连接。从环境准备、图形界面设置到各平台客户端配置,提供一站式解决方案,并包含常见问题排查与安全增强措施,帮助用户快速搭建个人远程访问网络。

weixin_30555125的博客 131

自动驾驶必备:5分钟搞懂gPTP如何实现μs级时间同步(附开源代码)

本文深入解析了gPTP协议在自动驾驶系统中实现微秒级时间同步的核心机制与工程实践。针对多传感器融合与跨域协同的严苛需求,文章拆解了gPTP的频率同步、对等延迟测量与时间偏移校正三步流程,并提供了基于linuxptp和AVnu gPTP两大开源代码库的实战配置指南与性能评估方法,助力开发者构建高精度、高可靠的车载时间同步网络。

weixin_29211309的博客 175

springboot集成mongoDB高级聚合查询,关联查询

使用该阶段符分组查询该。

m0_54850467的博客 1512

算法竞赛入门到进阶 --- 完整学习路线(含知识点讲解)

前言: 咳咳,接触算法竞赛也有一年了,却从来都没有进行过一次系统的学习,稀里糊涂的就这么搞了半年,如今,我决定认认真真的进行一次系统的复盘。嗯嗯,先把大体路线列出来,然后往后每天搞几篇,可能大三能完成,可能永远也不能写完这些,我只能慢慢来,一起共勉吧。冲了!(主要是太菜了,不系统学习下,怕是铜牌都拿不到呀!) 算法竞赛入门到进阶一、sort函数自定义排序二、c++容器的使用1.vector动态数组2.stack栈3.queue队列4.list链表5.set集合6.map映射三、二进制子集生成四、bfs.

qq_43514659的博客 2万+

Mongodb 管道之 $bucket和 $facet 用法详解

在MongoDB的聚合框架中,管道$bucket和$facet是两个功能强大的阶段操作符,分别用于数据的分组和多维度聚合。$bucket:适合明确分桶边界的单维度统计,如销售区间、年龄段分布。$facet:适用于复杂需求,需在单次查询中生成多个统计结果,如同时分析价格分布和地区销售趋势。正确选择两者可显著提升聚合效率,并简化数据处理流程。

一个平平无奇的程序媛 627

UE5在Ubuntu22.04.4下的高效开发环境配置指南

本文详细介绍了在Ubuntu 22.04.4系统上配置UE5高效开发环境的完整指南,包括系统准备、显卡驱动安装、UE5引擎编译与配置、开发工具链设置以及性能优化技巧。通过逐步指导,帮助开发者快速搭建稳定的UE5开发环境,解决常见问题,提升开发效率。

weixin_29251131的博客 387

告别版本过低提示!微信3.9登录修复与聊天记录无缝迁移全攻略

本文详细解析了微信3.9版本过低提示的根源,并提供了完整的修复方案和聊天记录迁移指南。通过专用修复工具绕过版本检测,以及新旧版本聊天记录目录对比,帮助用户实现无缝迁移。特别提醒备份重要数据,确保操作安全。

weixin_42535461的博客 3297

Mongodb聚合运算(二)

$bucket操作符 语法格式: { $bucket: { groupBy: <expression>, boundaries: [ <lowerbound1>, <lowerbound2>, ... ], default: <literal>, output: { <output1>: { <$accumulator expression> }, ...

RunTimeExcepti0n的博客 624

[STM32F103C8T6]W5500+Modbus TCP(HAL库)

本章节是博主学习Modbus TCP所写的一篇文章Modbus TCP是Modbus的一个分支,主要用到网口通信的,在工业上也用的很频繁,我们公司最近的项目就是用的W5500+modbus TCP来和PC端的上位机通信和交互的。虽然这个项目不是我在写代码,但是我都学了Modbus RTU了,那我也抽空学习一下Modbus TCP吧。本次的Modbus TCP不是博主写的,是一个大佬开源的一个W5500写的一个Mobus TCP代码,我在这个基础上自己写了主机读从机多个数据,和主机写从机寄存器的函数。

sinat_58149788的博客 4093

SpringBoot Mongodb Group By 查询统计

SQL示例 SELECT studentId,COUNT(*) FROM t_student; JAVA 示例 createTime 在mongoDb 存储格式为ISODate 例如: ISODate("2021-10-29T08:35:07.007Z") 示例1(时间条件) public List<Map> groupCountBySiteId() { //检索条件 Date startDate = DateUtil.parseDate("2022-03

cai454692590的博客 2043

一文快速教你如何下载国自然模版

5. 成功进入“相关文件查看”页面后,点击左侧的“项目申请文件“,如果你此次申请的是“面上项目”,选择对应的下拉框,找到对应的模版下载即可。6. 🫑们发现,在当前页面点击“青年科学基金项目”,左侧出现的是“原国家杰出青年科学基金项目”。7. 进入下一页后,点击“青年科学基金项目”,便可以在右侧找到🫑们要找的模版啦。2. 成功登陆后,点击1处的“首页”,在首页界面,再点击2处的“项目批准”。8. 点击上图3处的“文件详情”,就可以找到可以下载的模版啦(如下图)。3. 从“项目批准”进入后,点击“管理”。

薰珞婷紫小亭子的博客 2429

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Springboot聚合mongoDB,条件查询, 聚合统计

一.maven引包 <!-- mongodb --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> 二.mongo连接 yml配置 spring: data: mongodb:

AllenJoe666的博客 1664

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

SpringBoot+MongoDB查询操作(MongoTemplate)总结

SpringBoot+MangoDB查询操作(MongoTemplate)总结

qq_45690493的博客 7856

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

aggregation之$facet

aggregation之$facet

屹想天开 267

MongoDB aggregate 管道聚合查询

mongodb 管道查询

weixin_42555971的博客 2020

MongoDB JAVA Aggregate 管道聚合查询

java mongodb

weixin_42555971的博客 2896

springBoot整合mongodb之聚合操作

1.导入工具地址2.配置环境变量在环境变量path添加对应bin路径3.导入数据文件4.导入命令5.导出命令。

孟斌斌的博客 1190

系列十三、MongoDB聚合查询

MongoDB聚合框架(Aggregation Framework)是一个计算框架,它可以:①:作用在一个或者几个集合上;②:对集合中的数据进行一系列的运算;③:将这些数据转化为期望的形式;从效果而言,聚合框架相当于SQL中的 group by、left outer join、as等。

仰望星空,脚踏实地!安全感是自己给的,努力才是一辈子的安全感。 6062

MongoDB 高级查询 aggregate 聚合管道

1.MongoDB 聚合管道简介 使用聚合管道可以对集合中的文档进行变换和组合,常用于多表关联查询、数据的统计。 MongoDB 中使用 db.COLLECTION_NAME.aggregate([{<stage>},...]) 方法来构建和使用聚合管道,下图是官网给的实例,可以看出来聚合管道的用法还是比较简单的。 2.MongoDB Aggregation 管道操............

分享前端工程化、AI 应用、Agent 开发与大模型实践! 1038

SpringBoot中MongoDB的使用

SpringBoot中MongoDB的使用

YIYIYI 8367

MongoDB 聚合管道的文档关联查询($lookup)及管道合并($unionWith)

MongoDB中使用$lookup实现集合的关联查询、使用unionWith实现集合的管道的合并

Mointor 2397

MongoTemplate 常用查询

是Spring Data MongoDB提供的一个Java编程接口,用于操作MongoDB数据库。它提供了一系列方法和功能,以便进行数据的插入、更新、删除和查询等操作。使用MongoTemplate,你可以通过编写Java代码与MongoDB进行交互,而无需直接编写原生的MongoDB查询语句。它提供了一些便捷的方法,如save、insert、update和remove,用于对文档进行增删改操作。同时,它还支持复杂的查询条件和排序,以及聚合管道查询等高级功能。

CentOS 1961
下一篇: 单机Linux下搭建MongoDB副本集-三节点
harlan95
博客等级 码龄5年 2粉丝 5原创
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值