【mongoDB实战】聚合管道--$unwind
2017-06-27 11:48
369 查看
$unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
在做项目的时候碰上了这样的需求:
对weekday进行拆分:
使用$unwind可以将weekday中的每个数据都被分解成一个文档,并且除了weekday的值不同外,其他的值都是相同的.
对lunch进行拆分:
使用$unwind可以将lunch中的每个数据都被分解成一个文档,并且除了lunch的值不同外,其他的值都是相同的.
在做项目的时候碰上了这样的需求:
实例讲解:
{ "_id" : ObjectId("5951c5de567ebff0d5011fba"), "name" : "陈晓婵", "address" : "北京朝阳区", "weekday" : [ 1, 2, 3, 4, 5 ] }
对weekday进行拆分:
db.getCollection('chenxiaochantest').aggregate( [ { $unwind:"$weekday" } ] )
拆分结果:
/* 1 */ { "_id" : ObjectId("5951c5de567ebff0d5011fba"), "name" : "陈晓婵", "address" : "北京朝阳区", "weekday" : 1 } /* 2 */ { "_id" : ObjectId("5951c5de567ebff0d5011fba"), "name" : "陈晓婵", "address" : "北京朝阳区", "weekday" : 2 } /* 3 */ { "_id" : ObjectId("5951c5de567ebff0d5011fba"), "name" : "陈晓婵", "address" : "北京朝阳区", "weekday" : 3 } /* 4 */ { "_id" : ObjectId("5951c5de567ebff0d5011fba"), "name" : "陈晓婵", "address" : "北京朝阳区", "weekday" : 4 } /* 5 */ { "_id" : ObjectId("5951c5de567ebff0d5011fba"), "name" : "陈晓婵", "address" : "北京朝阳区", "weekday" : 5 }
使用$unwind可以将weekday中的每个数据都被分解成一个文档,并且除了weekday的值不同外,其他的值都是相同的.
实例讲解:
{ "_id" : ObjectId("5951ca15567ebff0d5011fbb"), "name" : "陈晓婵", "address" : "北京朝阳", "lunch" : [ { "food" : "baozi", "fruit" : "taozi" }, { "food" : "miaotiao", "fruit" : "xigua" } ] }
对lunch进行拆分:
db.getCollection('chenxiaochantest2').aggregate( [ { $unwind:"$lunch" } ] )
拆分结果:
/* 1 */ { "_id" : ObjectId("5951ca15567ebff0d5011fbb"), "name" : "陈晓婵", "address" : "北京朝阳", "lunch" : { "food" : "baozi", "fruit" : "taozi" } } /* 2 */ { "_id" : ObjectId("5951ca15567ebff0d5011fbb"), "name" : "陈晓婵", "address" : "北京朝阳", "lunch" : { "food" : "miaotiao", "fruit" : "xigua" } }
使用$unwind可以将lunch中的每个数据都被分解成一个文档,并且除了lunch的值不同外,其他的值都是相同的.
相关文章推荐
- MongoDB小结33 - 聚合管道【$unwind】
- MongoDB 聚合管道(一)(Aggregation Pipeline)
- MongoDB小结31 - 聚合管道【$skip】
- 【翻译】MongoDB指南/聚合——聚合管道
- MongoDB小结34 - 聚合管道【$group】
- MongoDB 聚合管道(Aggregation Pipeline)
- MongoDB小结32 - 聚合管道【$skip】
- MongoDB小结35 - 聚合管道【$sort】
- MongoDB 聚合管道(Aggregation Pipeline)
- Mongodb中数据聚合之聚合管道aggregate
- MongoDB 聚合管道(Aggregation Pipeline)
- MongoDB 聚合(管道与表达式)
- MongoDB聚合管道与SQL子句相对比
- MongoDB 聚合管道(Aggregation Pipeline)
- Mongodb 聚合管道(Aggregation Pipeline)
- 二、MongoDB的高级查询(聚合、游标、管道、索引)
- MongoDB小结27 - 聚合管道【$project】
- MongoDB 聚合管道(一)(Aggregation Pipeline)
- Mongodb 聚合管道
- MongoDB 聚合管道(Aggregation Pipeline)