我有 3 個檔案:
{
"id": 1,
"user": "Brian1",
"configs": [
"a",
"b",
"c",
"d"
]
}
----
{
"id": 2,
"user": "max_en",
"configs": [
"a",
"h",
"i",
"j"
]
}
----
----
{
"id": 3,
"user": "userX",
"configs": [
"t",
"u",
"s",
"b"
]
}
我想將所有“配置”陣列合并到一個陣列中而不重復,如下所示:
{
"configs": [
"a",
"b",
"c",
"d",
"h",
"i",
"j",
"t",
"u",
"s",
]
}
我嘗試了以下方法:
Aggregation.group("").addToSet("configs").as("configs") 和 { _id: "", 'configs': { $addToSet: '$configs' } }
第一個給出錯誤,因為我將欄位名留空(我不知道該放什么)。
第二個回傳一個合并的陣列,但有重復。
uj5u.com熱心網友回復:
當您想對所有檔案進行分組時,您需要添加 {_id: null}
這意味著對所有檔案進行分組。
可能你需要這個
db.collection.aggregate([
{
"$unwind": "$configs"
},
{
$group: {
_id: null,
configs: {
"$addToSet": "$configs"
}
}
}
])
但是當你需要在沒有匹配的情況下使用更大的集合時要小心。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422851.html
標籤:
