[英]Get Aggregate Data In MongoDB
這是上面圖片中提供的 mongo DB 文檔結構。 在那里你可以看到我們在 pages 數組下有一個xmlRequests 數組(Pages 是對象數組)。 所以每個會話都有包含一些對象的 pages 數組
我想做的事:
假設我們有 10 個具有相同結構的文檔,如上圖所示。 我想要一個數組中所有會話下所有頁面的聚合(統一)數組。 簡單來說,我想要一個數組中所有會話的 pages 數組。 (總計的)
像這樣:
{
pages : [] // array containing all the objects of request arrays under each session.
}
我需要一個統一的requests[]數組,其中包含一個數組中所有會話的所有請求。 我嘗試使用db.collection.aggregate([ ])但我不知道如何獲取文檔中的嵌套值並將所有這些值統一到一個對象數組中。
Mongo 代碼片段
{
"user": "abc",
"sessions": {
"12345": {
"pages": [
{
requests: [ {name: 'request1'}]
}
]
},
"23456": {
"pages": [
{
requests: [ {name: 'request1'}]
}
]
}
}
}
{
"user": "xyz",
"sessions": {
"12345": {
"pages": [
{
requests: [ {name: 'request1'}]
}
]
},
"23456": {
"pages": [
{
requests: [ {name: 'request1'}]
}
]
}
}
}
獲取集合中的所有請求數組並將它們合並為一個數組
您可以從$objectToArray開始,以便從未知鍵中檢索值。 然后你需要幾個$reduce / $concatArrays對來壓平數組數組。 $group可用於將所有請求收集到單個文檔中:
db.collection.aggregate([
{
$project: {
pages: {
$reduce: {
input: { $objectToArray: "$sessions" },
initialValue: [],
in: {
$concatArrays: [
"$$value",
{
$reduce: {
input: "$$this.v.pages",
initialValue: [],
in: { $concatArrays: [ "$$value", "$$this.requests" ] }
}
}
]
}
}
}
}
},
{
$group: {
_id: null,
pages: { $push: "$pages" }
}
},
{
$project: {
pages: {
$reduce: {
input: "$pages",
initialValue: [],
in: { $concatArrays: [ "$$value", "$$this" ] }
}
}
}
}
])
試試這個。 基本上我們展開第一個數組頁面,以便我們得到一個巨大的頁面列表。 然后我們將所有 xml 請求數組分組為一個大數組。 然后我們將它們合並到一個數組中並返回一個帶有鍵的對象 requests 包含最終數組
.aggregate([{
$unwind: “$pages”,
},
{
$group: {
_id: null,
xmlRequests: { $push: "$xmlRequests"}
}
},
{
$project: {
_id: 0,
requests: {
$reduce: {
input: "$xmlRequests",
initialValue: [],
in: {
$concatArrays: [ "$$this", "$$value"]
}
}
}
}
}])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.