我想將一個不存在的欄位投影到默認值
收藏A
{
_id: ObjectId("6013859ba0c3120034d08bfa"),
name: "A1",
refs:[
{id: ObjectId("6013859ba0c3120034d08bfb"), text: "ABC"},
{id: ObjectId("6013859ba0c3120034d08bfc"), text: "DEF"}
]
}
收藏B
{
_id: ObjectId("6013859ba0c3120034d08bfb"),
name: "B1",
altName: "b1"
}
{
_id: ObjectId("6013859ba0c3120034d08bfc"),
name: "B2"
}
預期輸出
{
"_id" : ObjectId("6013859ba0c3120034d08bfa"),
"name" : "A1",
"refs" : [
{
"id" : ObjectId("6013859ba0c3120034d08bfb"),
"text" : "ABC",
"name" : "B1",
"altName" : "b1"
},
{
"id" : ObjectId("6013859ba0c3120034d08bfc"),
"text" : "DEF",
"name" : "B2",
"altName" : "Unspecified"
}
]
}
就我而言,我只想在專案運算式中執行此操作。我在這個問題中嘗試過像這樣的專案
{
$project: {
...,
altName: {
$first: { $ifNull: [ "$$refsB.altName", "Unspecified" ] }
},
}
}
}
uj5u.com熱心網友回復:
您需要refsB.altName通過$first first檢索值,然后使用$ifNull檢查并分配值是否為空。
altName: {
$ifNull: [
{
$first: "$refsB.altName"
},
"Unspecified"
]
}
完整查詢
db.collectionA.aggregate([
{
$unwind: "$refs"
},
{
"$lookup": {
"from": "collectionB",
"localField": "refs.id",
"foreignField": "_id",
"as": "refsB"
}
},
{
$project: {
_id: 1,
name: 1,
refs: {
id: "$refs.id",
text: "$refs.text",
name: {
$first: "$refsB.name"
},
altName: {
$ifNull: [
{
$first: "$refsB.altName"
},
"Unspecified"
]
},
}
}
},
{
$group: {
_id: "$_id",
name: {
$first: "$name"
},
refs: {
$push: "$refs"
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362973.html
標籤:MongoDB
上一篇:為集合中的所有檔案更新陣列中的一兩個欄位-mongodb
下一篇:動態鏈接查詢
