簡體   English   中英

使用 mongodb 聚合合並到嵌套對象中

[英]Merge into a nested object using mongodb aggregation

我有一個 MongoDB 集合,其文檔結構類似於:

{
    "_id" : "xxx",
    "inner : {
        "foo" : 1,
        "bar" : 2
    }
}

數據庫版本為4.2.6

以及一個聚合管道,其倒數第二個階段是$project ,其結果文檔與以下內容匹配:

{
    "_id" : "xxx",
    "inner : {
        "baz" : 3
    }
}

接下來是合並到集合中的最后階段:

{
    "$merge" : {
        into: "myCollection",
        on: "_id",
        whenMatched: "merge",
        whenNotMatched: "discard"
    }
}

然而,結果是,現有的inner文檔字段被$merge結果覆蓋。 意義:

預期成績:

{
    "_id" : "xxx",
    "inner : {
        "foo" : 1,
        "bar" : 2,
        "baz" : 3
    }
}

實際結果:

{
    "_id" : "xxx",
    "inner : {
        "baz" : 3
    }
}

我怎樣才能克服這個問題?

“合並”選項合並根文檔,因此在您的查詢中替換inner字段。
嘗試用這個使用管道的合並替換合並。
我還沒有測試過,但我認為它會沒事的。
$$new變量是 mongo 定義的,用於引用來自管道的文檔。

{
    "$merge" : {
        into: "myCollection",
        on: "_id",
        whenMatched: 
          [{"$project": 
             {"_id": "$_id",
              "inner": {"$mergeObjects": ["$inner","$$new.inner"]}}}],
        whenNotMatched: "discard"
    }
}

接受的答案是一個很好的線索,盡管$project管道導致除_idinner之外的每個字段都被覆蓋。 這當然不是我想要的。

應該是顯而易見的選擇,只是使用$addFields代替:

 whenMatched:  [
     {"$addFields" :
         {"inner.baz": "$$new.baz"}
     }
 ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM