mongodb $unwind 聚合管道
阿新 • • 發佈:2019-01-12
$unwind
:將文件中的某一個數組型別欄位拆分成多條,每條包含陣列中的一個值。
需求:
{
"_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"
}
}
轉載來源:https://blog.csdn.net/chenxiaochan/article/details/73771879