Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort by date with aggregate request in mongodb

I would like to retrieve a list of values ​​that comes from the oldest document currently signed.But i failed to select a document absed on the date.Thanks

here is json :

    "ad" : "noc3",
    "createdDate" : ISODate(),
    "list" : [
            {
                    "id" : "p45",
                    "value" : 21,

            },
            {
                    "id" : "p6",
                    "value" : 20,             
            },
            {
                   "id" : "4578",     
                    "value" : 319
            }
   ]

and here my aggregate request :

db.friends.aggregate({$match:{advertiser:"noc3", {$sort:{timestamps:-1},{$limit:1} }},{$unwind:"$list"},{$project:{_id: "$list.id", value:{$add:[0]}}});
like image 793
jonn Avatar asked Jul 26 '13 10:07

jonn


People also ask

How do I sort data in MongoDB aggregate?

In MongoDb, the aggregation is assisted by several methods and operators that can perform different tasks. Among those operators, the $sort operator helps to sort the documents and return the documents in an organized order. And for group sorting in MongoDB, the $group operator is used with the $sort operator.

How do I sort an array in MongoDB aggregation?

To sort the whole array by value, or to sort by array elements that are not documents, identify the input array and specify 1 for an ascending sort or -1 for descending sort in the sortBy parameter.

How do I change the date format in aggregation in MongoDB?

If you have documents that store dates as Date objects, but you want to return them in a different format, you can use the $dateToString aggregate pipeline operator. The $dateToString operator converts the Date object to a string, and optionally allows you to specify a format for the resulting output.

How do you arrange data in ascending and descending order in MongoDB?

Ascending/Descending SortSpecify in the sort parameter the field or fields to sort by and a value of 1 or -1 to specify an ascending or descending sort respectively. When comparing values of different BSON types, MongoDB uses the following comparison order, from lowest to highest: MinKey (internal type) Null.


1 Answers

Your aggregate query is incorrect. You add the sort and limit to the match, but that's now how you do that. You use different pipeline operators:

db.friends.aggregate( [
    { $match: { advertiser: "noc3" } }, 
    { $sort: { createdDate: -1 } },
    { $limit: 1 },

Your other pipeline operators are bit strange too, and your code vs query mismatches on timestamps vs createdDate. If you add the expected output, I can update the answer to include the last bits of the query too.

like image 188
Derick Avatar answered Nov 04 '22 05:11

Derick