我有一個 mongo 集合,其中包含包含陣列的檔案:
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
我想獲得一個包含所有不同值的陣列,例如:
標簽:[“空白”,“紅色”,藍色“]和dim_cm:[14,21,22.85,30,10,15.25]
這可以通過聚合管道實作嗎?
uj5u.com熱心網友回復:
您可以$group使用$reduce和$setIntersection:
$group所有檔案,每個鍵創建一個陣列陣列- 用 展平每個陣列
$reduce并使用$setIntersection.
db.collection.aggregate([
{$group: {_id: null, tags: {$push: "$tags"}, dim_cm: {$push: "$dim_cm"}}},
{
$project: {
_id: 0,
tags: {
$setIntersection: [
{$reduce: {
input: "$tags",
initialValue: [],
in: {$concatArrays: ["$$value", "$$this"]}
}
}
]
},
dim_cm: {
$setIntersection: [
{$reduce: {
input: "$dim_cm",
initialValue: [],
in: {$concatArrays: ["$$value", "$$this"]}
}
}
]
}
}
}
])
看看它在操場上的例子是如何作業的
另一種方法是:
db.collection.aggregate([
{$unwind: "$tags"},
{
$group: {
_id: null,
tags: {$addToSet: "$tags"},
dim_cm: {$addToSet: "$dim_cm"
}
},
{$unwind: "$dim_cm"},
{$unwind: "$dim_cm"},
{
$group: {
_id: null,
tags: {$first: "$tags"},
dim_cm: {$addToSet: "$dim_cm"}
}
}
])
游樂場 - 放松
您可以將其拆分為兩個查詢,這將更快:
db.collection.aggregate([
{$unwind: "$tags"},
{
$group: {
_id: null,
tags: {$addToSet: "$tags"}
}
},
])
第三種選擇是:
db.collection.aggregate([
{
$project: {
_id: 0,
arr: {
$concatArrays: [
{$map: {input: "$tags", as: "item", in: {k: "tag", v: "$$item"}}},
{$map: {input: "$dim_cm", as: "item", in: {k: "dim_cm", v: "$$item"}}}
]
}
}
},
{$unwind: "$arr"},
{
$group: {
_id: null,
tags: {
$addToSet: {$cond: [{$eq: ["$arr.k", "tag"]}, "$arr.v", "$$REMOVE"]}
},
dim_cm: {
$addToSet: {$cond: [{$eq: ["$arr.k", "dim_cm"]}, "$arr.v", "$$REMOVE"]}
}
}
}
])
操場第三
uj5u.com熱心網友回復:
詢問
- 將兩者放在一個陣列中
- 放松
- 在小組時間檢查型別(字串與否)并放入正確的組
*這里的型別是不同的,如果它們是相同的型別,我們可以做另一個技巧,比如把它放在一個成對的陣列中,[[tag,cm] ...]其中第一個是標簽,第二個是cm,或者檔案陣列
如果你測驗的話如果可以的話,它會發送它的進展情況
玩蒙哥
aggregate(
[{"$project": {"tags-dim": {"$concatArrays": ["$tags", "$dim_cm"]}}},
{"$unwind": "$tags-dim"},
{"$group":
{"_id": null,
"tags":
{"$addToSet":
{"$cond":
[{"$eq": [{"$type": "$tags-dim"}, "string"]}, "$tags-dim",
"$$REMOVE"]}},
"dim_cm":
{"$addToSet":
{"$cond":
[{"$eq": [{"$type": "$tags-dim"}, "string"]}, "$$REMOVE",
"$tags-dim"]}}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/489406.html
上一篇:如何在包含許多物件的陣列中搜索,然后對其進行更新以不顯示重復項
下一篇:陣列重排序演算法
