[英]MongoDB - Aggregate - Filter on the last element in an array field in collection
我在 MongoDB 中有一個Devices集合,其結構如下:
{
"group": [
"group1"
]
},
{
"group": [
"group1",
"group2"
]
},
{
"group": []
},
{
"group": [
"group3",
"group4"
]
}
如何過濾或聚合文檔,以便只返回每個組數組的最后一個元素,包括空白數組?
預期結果:
["group1", "group2", "", "group4"]
您可以$group並使用$arrayElemAt來獲取最后一個元素。 此外,您需要$ifNull來指定默認值(空字符串):
db.collection.aggregate([
{
$group: {
_id: null,
lastElements: { $push: { $ifNull: [ { $arrayElemAt: [ "$group", -1 ] }, "" ] } }
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.