簡體   English   中英

MongoDB:如何將所有文檔合並到聚合管道中的單個文檔中

[英]MongoDB: How to merge all documents into a single document in an aggregation pipeline

我的當前聚合輸出如下:

[
    {
        "courseCount": 14
    },
    {
        "registeredStudentsCount": 1
    }
]

該數組有兩個文檔。 我想將所有文檔組合成一個文檔,其中包含 mongoDB 中的所有字段

{
    $group: {
      "_id": "null",
      data: {
        $push: "$$ROOT"
      }
    }
  }

當您將其添加為最后一個管道時,它會將所有文檔放在 data 下,但這里的 data 將是一個對象數組。

在你的情況下,它會是

{ "data":[
    {
        "courseCount": 14
    },
    {
        "registeredStudentsCount": 1
    }
] }

另一種方法是,

db.collection.aggregate([
  {
    $group: {
      "_id": "null",
      f: {
        $first: "$$ROOT",
        
      },
      l: {
        $last: "$$ROOT"
      }
    }
  },
  {
    "$project": {
      "output": {
        "courseCount": "$f.courseCount",
        "registeredStudentsCount": "$l.registeredStudentsCount"
      },
      "_id": 0
    }
  }
])

它不像第一個那樣動態。 由於您有兩個文檔,因此您可以使用這種方法。 它輸出

[
  {
    "output": {
      "courseCount": 14,
      "registeredStudentsCount": 1
    }
  }
]

在第二種方法中使用額外的管道

 {
    "$replaceRoot": {
      "newRoot": "$output"
    }
  }

你會得到輸出為

[
  {
    "courseCount": 14,
    "registeredStudentsCount": 1
  }
]
 db.collection.aggregate([
 {
   $group: {
    _id: 0,
     merged: {
    $push: "$$ROOT"
   }
   }
  },
 {
  $replaceRoot: {
  newRoot: {
    "$mergeObjects": "$merged"
   }
  }
 }
])

解釋:

  1. 通過 push 將輸出文檔分組到一個字段中
  2. 用合並的對象替換文檔根

游樂場

暫無
暫無

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

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