【发布时间】:2020-01-16 21:48:38
【问题描述】:
我有一个聚合可以概括为:
db.getCollection('originalCollection').aggregate([
$match: { //some filters }
$project: { //some transformations}
$facet: {
"collectionA": [ //some transformation steps ],
"collectionB": [ //some other transformation steps ]
}
...
现在我想使用id 字段与集合A 和B 进行类似SQL 的连接。例如,如果我在集合 A 中有此文档:
{
id: "A"
property1: "a value"
}
这个文档在集合B:
{
id: "A"
property2: "other value"
}
生成的集合必须包含:
{
id: "A",
property1: "a value",
property2: "other value"
}
我尝试作为下一个聚合步骤在集合 A 上使用 $map,它使用 $filter 来匹配集合 B 中具有相同 ID 的文档,但速度非常慢:
{
"$project": {
"tmpResult": {
"$map": {
"input": "$collectionA",
"as": "collectionADocument",
"in": {
"property1": "$$collectionADocument.property1",
"property2": {
"$arrayElemAt": [
{
"$filter": {
"input": "$collectionB",
"cond": {
"$eq": [
"$$collectionADocument.id",
"$$this.id"
]
}
}
},
0
]
}
}
}
}
}
}
在构面中实现两个集合连接的最快方法是什么?提前致谢!
【问题讨论】:
-
$filters 非常快,分享一下collectionA和collectionB数组有多少项。其他解决方案可能是$concatArrays [collectionA, collectionB]+$unwind+$group+$mergeObjects。您可以进行基准测试以选择最佳方式...
标签: mongodb mongodb-query aggregation-framework