簡體   English   中英

拉出對象數組並從數組中使用它們的字段(MongoDB 聚合框架)

[英]Pull out array of objects and use their fields out of the array (MongoDB aggregation framework)

我不知道這是否可行,但假設我有這樣的文件:

[
  {
    "L": [
      {
        "L1": 1
      }, 
      {
        "L6": 2
      }, 
      {
        "L2": 1
      }
    ], 
    "week": 26, 
    "weekEnd": "2020-06-28", 
    "weekStart": "2020-06-22"
  },
  {
    "L": [
      {
        "L5": 1
      }, 
      {
        "L2": 1
      }, 
      {
        "L3": 1
      }
    ], 
    "week": 19, 
    "weekEnd": "2020-05-10", 
    "weekStart": "2020-05-04"
  }, 
]

正如大家所看到的,數組L可以有不同的對象,其中包含L1, L2, L3, ..., L30等字段。
我想從L數組中取出每個 object 的字段。
預期結果:

[
  {
    "L1": 1,
    "L6": 2,
    "L2": 1, 
    "week": 26, 
    "weekEnd": "2020-06-28", 
    "weekStart": "2020-06-22"
  },
  {
    "L5": 1,
    "L2": 1,
    "L3": 1, 
    "week": 19, 
    "weekEnd": "2020-05-10", 
    "weekStart": "2020-05-04"
  }
]

我可以“從頭開始”做到這一點,但我必須在$project階段一個一個地編寫每個字段。 有自動的方法嗎?

您可以使用$mergeObjects (從 v3.6 開始提供)來合並數組中對象的所有鍵。 首先,您必須合並數組L中的對象,然后您必須將結果與根文檔$$ROOT合並

db.collection.aggregate({
  $replaceRoot: { // 3. replace the result as root document
    newRoot: {
      $mergeObjects: [ // 2. merge with root document
        {
          $mergeObjects: "$L" // 1. merge objects in array L
        },
        "$$ROOT"
      ]
    }
  }
},
{
  $project: { // remove original L array
    L: false
  }
})

蒙戈游樂場

如果您使用的是 v4.2 或更高版本,則可以使用以下略短的語法

db.collection.aggregate({
  $replaceWith: {
    $mergeObjects: [
      {
        $mergeObjects: "$L"
      },
      "$$ROOT"
    ]
  }
},
{
  $unset: "L"
})

暫無
暫無

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

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