W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
聚合階段。使用指定的數(shù)組字段中的每個(gè)元素,對(duì)文檔進(jìn)行拆分。拆分后,文檔會(huì)從一個(gè)變?yōu)橐粋€(gè)或多個(gè),分別對(duì)應(yīng)數(shù)組的每個(gè)元素。
使用指定的數(shù)組字段中的每個(gè)元素,對(duì)文檔進(jìn)行拆分。拆分后,文檔會(huì)從一個(gè)變?yōu)橐粋€(gè)或多個(gè),分別對(duì)應(yīng)數(shù)組的每個(gè)元素。
unwind 有兩種使用形式:
unwind(<字段名>)
unwind({
path: <字段名>,
includeArrayIndex: <string>,
preserveNullAndEmptyArrays: <boolean>
})
字段 | 類型 | 說(shuō)明 |
---|---|---|
path | string | 想要拆分的數(shù)組的字段名,需要以 $ 開(kāi)頭。 |
includeArrayIndex | string | 可選項(xiàng),傳入一個(gè)新的字段名,數(shù)組索引會(huì)保存在這個(gè)新的字段上。新的字段名不能以 $ 開(kāi)頭。 |
preserveNullAndEmptyArrays | boolean | 如果為 true ,那么在 path 對(duì)應(yīng)的字段為 null 、空數(shù)組或者這個(gè)字段不存在時(shí),依然會(huì)輸出這個(gè)文檔;如果為 false ,unwind 將不會(huì)輸出這些文檔。默認(rèn)為 false 。 |
假設(shè)我們有一個(gè) products 集合,包含數(shù)據(jù)如下:
{ "_id": "1", "product": "tshirt", "size": ["S", "M", "L"] }
{ "_id": "2", "product": "pants", "size": [] }
{ "_id": "3", "product": "socks", "size": null }
{ "_id": "4", "product": "trousers", "size": ["S"] }
{ "_id": "5", "product": "sweater", "size": ["M", "L"] }
我們根據(jù) size 字段對(duì)這些文檔進(jìn)行拆分
db.collection('products')
.aggregate()
.unwind('$size')
.end()
輸出如下:
{ "_id": "1", "product": "tshirt", "size": "S" }
{ "_id": "1", "product": "tshirt", "size": "M" }
{ "_id": "1", "product": "tshirt", "size": "L" }
{ "_id": "4", "product": "trousers", "size": "S" }
{ "_id": "5", "product": "sweater", "size": "M" }
{ "_id": "5", "product": "sweater", "size": "L" }
我們根據(jù) size 字段對(duì)文檔進(jìn)行拆分后,想要保留原數(shù)組索引在新的 index 字段中。
db.collection('products')
.aggregate()
.unwind({
path: '$size',
includeArrayIndex: 'index'
})
.end()
輸出如下:
{ "_id": "1", "product": "tshirt", "size": "S", "index": 0 }
{ "_id": "1", "product": "tshirt", "size": "M", "index": 1 }
{ "_id": "1", "product": "tshirt", "size": "L", "index": 2 }
{ "_id": "4", "product": "trousers", "size": "S", "index": 0 }
{ "_id": "5", "product": "sweater", "size": "M", "index": 0 }
{ "_id": "5", "product": "sweater", "size": "L", "index": 1 }
注意到我們的集合中有兩行特殊的空值數(shù)據(jù):
...
{ "_id": "2", "product": "pants", "size": [] }
{ "_id": "3", "product": "socks", "size": null }
...
如果想要在輸出中保留 size 為空數(shù)組、null,或者 size 字段不存在的文檔,可以使用 preserveNullAndEmptyArrays 參數(shù)
db.collection('products')
.aggregate()
.unwind({
path: '$size',
preserveNullAndEmptyArrays: true
})
.end()
輸出如下:
{ "_id": "1", "product": "tshirt", "size": "S" }
{ "_id": "1", "product": "tshirt", "size": "M" }
{ "_id": "1", "product": "tshirt", "size": "L" }
{ "_id": "2", "product": "pants", "size": null }
{ "_id": "3", "product": "socks", "size": null }
{ "_id": "4", "product": "trousers", "size": "S" }
{ "_id": "5", "product": "sweater", "size": "M" }
{ "_id": "5", "product": "sweater", "size": "L" }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: