Getting a document with maximum internal array size in MongoDB

Mongo Document example:

{
    "_id": "128374",
    "x": [
        {
            "i": "83847575",
            "y": [
                {
                    "i": "9389489283",
                    "t": "2014-04-11T20:46:57+0000"
                },
                {
                    "i": "9389489284",
                    "t": "2014-04-11T20:47:57+0000"
                }
            ]
        },
        {
            "i": "83847576",
            "y": [
                {
                    "i": "2382349385",
                    "t": "2014-01-15T23:43:29+0000"
                },
                {
                    "i": "9389489286",
                    "t": "2014-04-11T20:47:57+0000"
                },
                {
                    "i": "9389489286",
                    "t": "2014-04-11T20:49:57+0000"
                }
            ]
        }
    ]
}

How do you get the maximum number of internal arrays of 'y' for each document? The problem I'm trying to solve is to get the record with the maximum amount of "y". Thank!

The following gives me the total number of "y".

db.coll.aggregate( 
{ "$unwind" : "$x" } , 
{ "$project" : { "x" : "$x" } } , 
{ "$unwind" : "$x.y" }, 
{ "$group" : { _id : null, number : { $sum : 1 } } } )
+4
source share
3 answers

If you want to find a document in a collection that contains most of the elements "y", the way to do this within the aggregation would be as follows:

db.coll.aggregate( {$unwind:"$x"},
                   {$project:{ysize:{$size:"$x.y"}}},
                   {$group:{_id:"$_id",numYs:{$sum:"$ysize"}}},
                   {$sort: {numYs:-1} },
                   {$limit: 1 }
)

$size ( 2.6) y , , , "y" .

.

y . , y , , ysize:

db.coll.aggregate( {$unwind:"$x"},
                   {$project:{ysize:{$size:"$x.y"}}},
                   {$sort: {ysize:-1} },
                   {$limit: 1 }
)
+2

, - . "i", , "y":

db.collection.aggregate([
    { "$unwind" : "$x" }, 
    { "$unwind" : "$x.y" }, 
    { "$group" : { 
        "_id" : {
          "_id": "$_id",  
          "xi":"$x.i"
        },
        "number" : { "$sum" : 1 } 
    }},
    { "$sort": { "number": -1 }},
    { "$limit": 1 } 
])

, "_id", , "y", , .

+1

Try this aggregation request.

db.collection.aggregate([
    {$unwind: '$x'},
    {$group: {_id: null, maxLengthOfYArray: {$max: {$size: '$x.y'}}}}
])
0
source

Source: https://habr.com/ru/post/1538141/


All Articles