簡體   English   中英

MongoDB聚合-合並對象的數組

[英]MongoDB Aggregation - Merge arrays of an object

我想使用聚合框架在MongoDB 3.4中獲取對象中所有數組的並集:

這是輸入:

{ 
  _id: "001",
  name: "something",
  important_part: {
    foo: [1,2,3],
    bar: [4,5],
    x: [6,7]
  }
}

這應該是輸出:

{ 
  _id: "001",
  name: "something",
  merged_arrays: [1,2,3,4,5,6,7]
}

最棘手的部分是,在important_part對象中的字段是動態的,而且我不認為$ setUnion運營商都可以使用,因為它需要陣列方面的准確名單。

有人可以幫我嗎?

提前Thx

您可以在3.4中使用以下匯總。

$objectToArray將對象轉換為鍵值對數組,並將$reduce$concatArrays

db.col.aggregate({
  "$addFields":{
    "merged_arrays":{
      "$reduce":{
        "input":{"$objectToArray":"$important_part"},
        "initialValue":[],
        "in":{"$concatArrays":["$$value", "$$this.v"]}
      }
    }
  }
})

暫無
暫無

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

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