我正在嘗試添加一個新的帶條件的子欄位。 在該欄位已經存在的情況下,我不會覆寫它。 在條件沒有滿足的情況下,我不希望添加父物件。
以下是我的集合:
{type: "A", object: {a: ""/span>, b: "foo"}}。
{type: "A"/span>, object: {a: ""}}。
{type: "A"/span>}。
{type: "B"}, {type: "B"}
這是我的集合 :
{
$addFields: {
"object.b": {
$cond: {
if: {$eq: ["$type","A"]},
then: {$ifNull: ["$object.b", "bar"]>,}
else: "$DROP"。
}
}
}
$DROP不是一個聚合命令,但在其他情況下,我不想添加新的欄位。
它將不會創建b欄位,但是父物件仍然存在。
這是我目前的結果 :
{type: "A"/span>, "object"/span>: {a: ""/span>, b: "foo"}}。
{type: "A"/span>, "object"/span>: {a: ""/span>, b: "bar"}}。
{type: "A"/span>, "object"/span>: {b: "bar"}}。
{type: "B", "物件": {}}。
這就是我想要的:
{type: "A", object: {a: ""/span>, b: "foo"}}。
{type: "A"/span>, object: {a: ""/span>, b: "bar"}}。
{type: "A"/span>, object: {b: "bar"}}。
{type: "B"}, {type: "B"}.
我們將非常感謝您的幫助。
uj5u.com熱心網友回復:
這個聚合查詢將給你帶來想要的結果:
這個聚合查詢將給你帶來想要的結果。
db.collection.aggregate( [
{
$addFields: {
object: {
$cond: {
if: { $eq: [ "$type", "A"] 。},
then: {
$mergeObjects: [
"$object",
{ b: { $ifNull: [ "$object.b", "bar" ] } }
]
},
else: "$REMOVE"。
}
}
}
}
])
注意$REMOVE是一個聚合系統變數。
uj5u.com熱心網友回復:
當一個$set添加一個路徑時,所有的路徑都會被添加,即使你最后到了$REMOVE這將只影響路徑的最后一個,其余的將已經被添加見例
查詢
$set與switch case從物件開始- 如果物件不存在
- 如果型別A添加
{object :{"b" : "bar"}} - else
$$REMOVE
- 如果型別A添加
- $type = "A" AND (not-value "$object.b")
增加{"b" : "bar"}(這種情況也包括object:null的情況) - else
保持舊值(另一種型別,或b有價值)
也許它可以更小,但我們要檢查很多東西(見例子中所有資料的情況)
- 物件存在/為空/不存在
- 型別A/not 。
- b存在/為空/為值 。
db.collection.aggregate( [
{
"$set"/span>: {
"object": {
"$switch": {
"branches": [
{
"case": {
"$eq": [
{
"$type": "$object": "$type".
},
"missing"
]
},
"then"/span>: {
"$cond"/span>: [
{
"$eq": [
"$type",
"A"。
]
},
{
"b": "b": "bar".
},
"$REMOVE"。
]
}
},
{
"case": {
"$and": [
{
"$eq": [
"$type",
"A"。
]
},
{
"$or": [
{
"$eq": [
"$object.b",
null。
]
},
{
"$eq": [
{
"$type": "$object.b"。
},
"missing"
]
}
]
}
]
},
"then": {
"$mergeObjects"/span>: [
"$object",
{
"b": "bar".
}
]
}
}
],
"default": "$object"。
}
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324509.html
標籤:
