Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

mongodb - Sorting aggregation addToSet result

Is there a way to get result of $addToSet as sorted array ?

I tried to expand the pipeline and $unwind the array, sort it and group it again , but still the result isn't sorted.

The arrays are pretty big and i try to avoid sort them in the the application.


Document Example :

    {
      "_id" : ObjectId("52a84825cc8391ab188b4567"),
      "id" : 129624
      "message" : "Sample",
      "date" : "12-09-2013,17:34:34",
      "dt" : ISODate("2013-12-09T17:34:34.000Z"),

    }

Query :


    db.uEvents.aggregate(
    [
      {$match : {dt : {$gte : new Date(2014,01,01) , $lt : new Date(2015,01,17)}}}
      ,{$sort : {dt : 1}}
      , {$group : {
        _id : {
                id : "$id"
                , year : {'$year' : "$dt"}
                , month : {'$month' : "$dt"}
                , day : {'$dayOfMonth' : "$dt"}
            }
        ,dt : {$addToSet : "$dt"}

      }}    
    ]

    );

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes it is possible, but approach it differently. I'm just provide my own data for this, but you'll get the concept.

My Sample:

{ "array" : [  2,  4,  3,  5,  2,  6,  8,  1,  2,  1,  3,  5,  9,  5 ] }

I'm going to "semi-quote" the CTO on this and state that Sets are considered to be unordered.

There is an actual JIRA, Google groups statement that goes something like that. So let's take it from "Elliot" and accept that this will be the case.

So if you want an ordered result, you have to massage that way with stages like this

db.collection.aggregate([

    // Initial unwind
    {"$unwind": "$array"},

    // Do your $addToSet part
    {"$group": {"_id": null, "array": {"$addToSet": "$array" }}},

    // Unwind it again
    {"$unwind": "$array"},

    // Sort how you want to
    {"$sort": { "array": 1} },

    // Use $push for a regular array
    {"$group": { "_id": null, "array": {"$push": "$array" }}}

])

And then do whatever. But now your array is sorted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...