Spring data mongodb 聚合查询(aggregation) 之 unwind

unwind:分解一个文档中的数组字段(例如数组大小为n) 为 (n)个文档

官方案例:

inventory数据:{ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] }
执行:db.inventory.aggregate( [ { $unwind : "$sizes" } ] )
结果:{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }

注:

1 includeArrayIndex:给每个数组的元素增加序号

db.inventory.aggregate( [ { $unwind: { path: "$sizes", includeArrayIndex: "arrayIndex" } } ] )
{ "_id" : 1, "item" : "ABC", "sizes" : "S", "arrayIndex" : NumberLong(0) }
{ "_id" : 1, "item" : "ABC", "sizes" : "M", "arrayIndex" : NumberLong(1) }
{ "_id" : 1, "item" : "ABC", "sizes" : "L", "arrayIndex" : NumberLong(2) }

2 preserveNullAndEmptyArrays:default:false 如果是true,将包括null,空,或者缺失

数据:

{ "_id" : 1, "item" : "ABC", "sizes": [ "S", "M", "L"] }
{ "_id" : 2, "item" : "EFG", "sizes" : [ ] }
{ "_id" : 3, "item" : "IJK", "sizes": "M" }
{ "_id" : 4, "item" : "LMN" }
{ "_id" : 5, "item" : "XYZ", "sizes" : null }

结果:

db.inventory.aggregate( [
   { $unwind: { path: "$sizes", preserveNullAndEmptyArrays: true } }
] )
{ "_id" : 1, "item" : "ABC", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC", "sizes" : "L" }
{ "_id" : 2, "item" : "EFG" }
{ "_id" : 3, "item" : "IJK", "sizes" : "M" }
{ "_id" : 4, "item" : "LMN" }
{ "_id" : 5, "item" : "XYZ", "sizes" : null }


Spring data mongodb:

 TypedAggregation agg = Aggregation.newAggregation(Role.class,
                Aggregation.unwind("sizes","arrayIndex",true)
        );
        AggregationResults result = mongoTemplate.aggregate(agg,Document.class);
        result.getMappedResults().forEach(document -> System.out.println(document));

注意:

返回的数据可以用org.bson.Document 来接收,也可以自定义实体类来接收


你可能感兴趣的:(spring,data,mongodb)