我有 2 个系列 A 和 B。
集合A记录如下:
{
"_id" : int,
"my_id" : int,
"date" : date,
"name" : string
}
集合B记录如下:
{
"_id": int
"status":string
}
对于特定 id,集合 A 上可以有无限条记录,集合 B 中最多可以有 1 条记录。这两个集合之间的公共字段是集合 A 中的“my_id”和集合 B 中的“_id”。
案例很少:
{
"_id" : int,
"status" : string,
"orders" :
[
{
"_id" : int,
"my_id" : int,
"date" : date,
"name" : string
},
{
"_id" : int,
"my_id" : int,
"date" : date,
"name" : string
},
...
]
}
{
"_id" : int,
"status" : string
}
{
"_id" : int,
"orders" :
[
{
"_id" : int,
"my_id" : int,
"date" : date,
"name" : string
},
{
"_id" : int,
"my_id" : int,
"date" : date,
"name" : string
},
...
]
}
如果有一种方法只需打一个电话,我将不胜感激。 我尝试过聚合管道,但没有成功支持所有 3 种情况。
这是我的尝试之一,但不支持第三种情况:
db.getCollection("collectionB").aggregate([
{
$match: {
"_id": givenId
}
},
{
$lookup: {
"from":"collectionA",
"localField": "_id",
"foreignField": "my_id",
"as": "orders"
}
},
{
$project: {
"status": 1,
"orders": {
"$cond": {
"if": {
"$eq": ["$orders", []]
},
"then": "$$REMOVE",
"else": "$orders"
}
}
}
}
])
可以先从集合B开始聚合来处理情况1和2。然后,
$unionWith
集合A到$group
将它们放入案例3中。
db.colB.aggregate([
{
"$match": {
_id: {
$in: [
1,
2,
3
]
}
}
},
{
"$lookup": {
"from": "colA",
"localField": "_id",
"foreignField": "my_id",
"as": "orders"
}
},
{
"$set": {
"orders": {
"$cond": {
"if": {
$eq: [
[],
"$orders"
]
},
"then": "$$REMOVE",
"else": "$orders"
}
}
}
},
{
"$unionWith": {
"coll": "colA",
"pipeline": [
{
"$match": {
_id: {
$in: [
1,
2,
3
]
}
}
},
{
"$lookup": {
"from": "colB",
"localField": "my_id",
"foreignField": "_id",
"as": "orders"
}
},
{
"$match": {
"orders": []
}
},
{
"$unset": "orders"
},
{
"$group": {
"_id": "$_id",
"orders": {
"$push": "$$ROOT"
}
}
}
]
}
}
])