Domanda

I have a collection named event.

I have an aggregation query as follows

db.event.aggregate([
    { "$group": { 
       "_id":{ 
           "UserId":"$TracInfo.UserId",
           "SessionId":"$TracInfo.SessionId"
       },
       "EventName":{ "$push": {
           "Name":"$Name",
           "Time":"$Timestamp"
       }}
   }},                    
   { "$out" :"demo" }
])

Its output is as follows :

{
    "result":[
        {
            "_id" : {
                "UserId" : "pawan",
                "SessionId" : "q69lIFHcpsCRgxtbJu1v"
            },
            "EventName" : [
                {
                    "Name" : "PREMISES MAP DELETED",
                    "Time" : NumberLong("1336090020090")
                },
                {
                    "Name" : "SCREEN STOPPED",
                    "Time" : NumberLong("1336090020010")
                },
                {
                    "Name" : "SETTINGS CHANGED",
                    "Time" : NumberLong("1336090020030")
                },
                {
                    "Name" : "PREMISES MAP DELETED",
                    "Time" : NumberLong("1336090020100")
                },
                {
                    "Name" : "SCREEN STARTED",
                    "Time" : NumberLong("1336090020330")
                },
                ...
        },
            ...
    ]
}

I want to sort EventName array of each document in result on Time value.

Is there any way to do it?

I have tried

{$sort:{"EventName.Time":1}} 

But it did not work.

È stato utile?

Soluzione

First make sure you have an index on Timestamp to avoid a performance hit.

Second, use this aggregation:

db.event.aggregate([
                  { $sort: { Timestamp:1 } },
                  { $group:
                    { _id:{"UserId":"$TracInfo.UserId","SessionId":"$TracInfo.SessionId"},
                      EventName:{$push:{"Name":"$Name","Time":"$Timestamp"}}}},                   
                  {$out:"demo"}
                 ])

Altri suggerimenti

Sort the timestamp before pushing it in array.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top