我是 mongo db 的新手,在這里我正在嘗試將 mysql 查詢轉換為 mongo db 查詢。
在這里,我必須在沒有任何條件的情況下將 mongodb 中 2 個集合中的一些欄位合并。兩個集合中都沒有公共欄位。下面提到了我的查詢,我只能看到“account_id”、“account_name”和連接的輸出。我無法看到我試圖在聯合查詢中投影的輸出未顯示在輸出中。誰能幫我解決這個問題。
db.accounts.aggregate(
{
"$unionWith": {
"coll": "parent_child", "pipeline": [
{
"$project": {
"child_id":"$CHILD_ID",
"name":"$NAME"
}
}
]
}
},
{
"$project":{
"account_id":"$ACCOUNT_ID",
"name":"$ACCOUNT_NAME"
}
}
)
為了您的理解,我發布了 mysql 查詢。
select p.CHILD_ID as account_id,p.NAME as name from parent_child p union select a.ACCOUNT_ID as account_id,a.ACCOUNT_NAME as name from account a
提供兩個集合的樣本記錄:
1.accounts
[{account_id:1,
name:"abc"},
{account_id:2,
name:"test"}]
2. parent_child:
[{CHILD_ID:23
NAME:"test child"},
[CHILD_ID:34,
NAME:"test1]}
預期輸出:
[{account_id:1,
name:"abc"},
{account_id:2,
name:"test"},
{account_id:21,
name:"test child"},
{account_id:34,
name:"test2"}]
uj5u.com熱心網友回復:
如果我理解正確,可以這樣做,但不建議這樣做,因為它將兩個集合中的所有檔案組合成一個大檔案:
db.accounts.aggregate([
{
$group: {
_id: 0,
accounts: {$push: {account_id: "$account_id", name: "$name"}}
}
},
{
$lookup: {
from: "parent_child",
let: {},
pipeline: [
{$project: {account_id: "$CHILD_ID", name: "$NAME", _id: 0}}
],
as: "parent_child"
}
},
{
$project: {
res: {$concatArrays: ["$accounts", "$parent_child"]},
_id: 0
}
}
])
看看它在操場上的例子是如何作業的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487238.html
