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

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

官方案例:mongodb

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:给每一个数组的元素增长序号
app

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,空,或者缺失
spa

数据:code

{ "_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:get

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

注意:it

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