我試圖聚合 2 個集合,它在陣列的第一層作業,但我不知道如何在下一層做。這是有資料的。
"app": [
{
"_id": "6364da3dc6cded87a8d74084",
"name": "app1",
"provider_tenants": [
{
"_id": "6364871d84eedd81331c60eb",
"tenants": [
{
"path": "path1",
"_id": "6364872d84eedd81331c60ec",
}
]
},
{
"_id": "63579dd4539180517fd51d71",
"tenants": [
{
"path": "path2",
"_id": "636485fa84eedd81331c60e6"
}
]
}
]
}
],
"details_provider": [
{
"_id": "63579dd4539180517fd51d71",
"name": "details_aaaaaa",
"tenants": [
{
"name": "xxxxx",
"redirect_uri": "www.asdf.com",
"_id": "636485fa84eedd81331c60e6"
},
{
"name": "zzzzz",
"redirect_uri": "www.zxcv.com",
"_id": "6364860684eedd81331c60e7"
}
]
},
{
"_id": "6364871d84eedd81331c60eb",
"name": "details_bbbbbb",
"tenants": [
{
"name": "yyyyy",
"redirect_uri": "www.qwer.com",
"_id": "6364872d84eedd81331c60ec"
}
]
}
]
這是我所做的結果。mongoplayground
接下來我應該怎么做才能得到我想要的結果?我想要的結果看起來像這樣。
[
{
"_id": "6364da3dc6cded87a8d74084",
"name": "app1",
"provider_tenants": [
{
"_id": "6364871d84eedd81331c60eb",
"name": "details_bbbbbb",
"tenants": [
{
"_id": "6364872d84eedd81331c60ec",
"name": "yyyyy",
"redirect_uri": "www.qwer.com",
"path": "path1",
}
]
},
{
"_id": "63579dd4539180517fd51d71",
"name": "details_aaaaaa",
"tenants": [
{
"_id": "636485fa84eedd81331c60e6",
"name": "xxxxx",
"redirect_uri": "www.asdf.com",
"path": "path2",
}
]
}
]
}
]
uj5u.com熱心網友回復:
稍微擴展您的管道,這是您可以做到的一種方法。
db.app.aggregate([
{
$lookup: {
from: "details_provider",
localField: "provider_tenants._id",
foreignField: "_id",
as: "provider"
}
},
{
"$project": {
"name": 1,
"provider_tenants": {
"$map": {
"input": "$provider_tenants",
"as": "ps",
in: {
"$let": {
"vars": {
"d_prov": {
"$first": {
"$filter": {
"input": "$provider",
"as": "prov",
"cond": {"$eq": ["$$ps._id", "$$prov._id"]}
}
}
}
},
"in": {
$mergeObjects: [
"$$ps",
{
"name": "$$d_prov.name",
"tenants": {
"$map": {
"input": "$$ps.tenants",
"as": "tens",
"in": {
"$mergeObjects": [
"$$tens",
{
"$first": {
"$filter": {
"input": "$$d_prov.tenants",
"cond": {"$eq": ["$$tens._id", "$$this._id"]}
}
}
}
]
}
}
}
}
]
}
}
}
}
}
}
}
])
在mongoplayground.net上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532493.html
上一篇:MongoDB聚合回傳一個空陣列
