簡體   English   中英

如何在數組元素的索引上分組文檔?

[英]How to group documents on index of array elements?

我正在尋找一種方法來獲取這樣的數據

{ "_id" : 5, "count" : 1, "arr" : [ "aga", "dd", "a" ] },
{ "_id" : 6, "count" : 4, "arr" : [ "aga", "ysdf" ] },
{ "_id" : 7, "count" : 4, "arr" : [ "sad", "aga" ] }

我想根據arr的第1項(索引)來計算總數。 在另一個聚合中,我想對arr數組中的第1項和第2項執行相同的操作。

我嘗試過使用unwind,但這會破壞數據,然后層次結構就會丟失。

我也試過用

$group: {
    _id: {
        arr_0:'$arr.0'
    },
    total:{
        $sum: '$count'
    }
}

但結果是空白數組

實際上,您不能使用點表示法按元素在指定的索引處對文檔進行分組。 兩個你有兩個選擇:

首先在MongoDB 3.2中使用$arrayElemAt運算符new的最佳方式。 它返回數組中指定索引處的元素。

db.collection.aggregate([
    { "$group": {
        "_id": { "$arrayElemAt": [ "$arr", 0 ] }, 
        "count": { "$sum": 1 }
    }}
])

從MongoDB 3.0版向后,您將需要對數組進行反規范化,然后在第一次$group by _id並使用$first運算符返回數組中的第一項。 從那里您需要使用該值重新組合您的文檔並使用$sum來獲得總和。 但這只適用於第一個和最后一個索引,因為MongoDB還提供$last運算符。

db.collection.aggregate([
    { "$unwind": "$arr" }, 
    { "$group": { 
        "_id": "$_id", 
        "arr": { "$first":  "$arr" }
    }}, 
    { "$group": {
        "_id": "$arr", 
        "count": { "$sum": 1 }
    }}
])

產生這樣的東西:

{ "_id" : "sad", "count" : 1 }
{ "_id" : "aga", "count" : 2 }

要使用數組中位置p元素進行分組,您將有更好的機會使用mapReduce函數。

var mapFunction = function(){ emit(this.arr[0], 1); };
var reduceFunction = function(key, value) { return Array.sum(value); };
db.collection.mapReduce(mapFunction, reduceFunction, { "out": { "inline": 1 } } )

哪個回報:

{
        "results" : [
                {
                        "_id" : "aga",
                        "value" : 2
                },
                {
                        "_id" : "sad",
                        "value" : 1
                }
        ],
        "timeMillis" : 27,
        "counts" : {
                "input" : 3,
                "emit" : 3,
                "reduce" : 1,
                "output" : 2
        },
        "ok" : 1
}

暫無
暫無

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

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