简体   繁体   中英

Mongodb - Aggregate Sorting by Restricted Array Elements

I have the following documents and here I want to sort them by the fields 'ranks.rank' within a restricted range.

How to do this kind of sorting? 'ranks.date': { '$gte': 20200516 }

I have tried something like

{ $match: selector },
{
  $project: {
    views: 1,
    'ranks': {
      $cond: {
        if: { $gte: ["$ranks.date", 20200516] },
        then: "$ranks",
        else: "$$REMOVE"
      }
    },
  }
},
{ $addFields: { totalRank: { $sum: '$ranks.rank' } } },
{ $sort: { 'totalRank': 1 } }

Documents

{ 
    "_id" : "Qvpbjpjqexko4XFGH", 
    "views" : NumberInt(15), 
    "ranks" : [
        {
            "date" : NumberInt(20200415), 
            "rank" : NumberInt(1)
        }, 
        {
            "date" : NumberInt(20200418), 
            "rank" : NumberInt(13)
        }, 
        {
            "date" : NumberInt(20200503), 
            "rank" : NumberInt(1)
        }
    ]{ 
    "_id" : "bLQKR39qmJcwuzm8r", 
    "views" : NumberInt(16), 
    "ranks" : [
        {
            "date" : NumberInt(20200415), 
            "rank" : NumberInt(1)
        }, 
        {
            "date" : NumberInt(20200418), 
            "rank" : NumberInt(12)
        }, 
        {
            "date" : NumberInt(20200501), 
            "rank" : NumberInt(2)
        }, 
        {
            "date" : NumberInt(20200521), 
            "rank" : NumberInt(1)
        }
    ]

It looks like your post is mostly code; please add some more details.

I think i figured out

        { $match: selector },

        {
            $project: {
                views: 1,
                ranks: {
                    $filter: {
                        input: "$ranks",
                        as: "rank",
                        cond: { $gte: ["$$rank.date", monAgo] }
                    }
                },
            },
        },

        { $addFields: { totalRank: { $sum: '$ranks.rank' } } },
        { $sort: { 'totalRank': -1 } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM