javascript - How can I sort array by a field inside a MongoDB document -


i have document called question

var questionschema = new schema({     title: {         type: string,         default: '',         trim: true     },     body: {         type: string,         default: '',         trim: true     },     user: {         type: schema.objectid,         ref: 'user'     },     category: [],     comments: [{         body: {             type: string,             default: ''         },         root: {             type: string,             default: ''         },         user: {             type: schema.types.objectid,             ref: 'user'         },         createdat: {             type: date,             default: date.now         }     }],     tags: {         type: [],         get: gettags,         set: settags     },     image: {         cdnuri: string,         files: []     },     createdat: {         type: date,         default: date.now     } }); 

as result, need sort comments root field, example

i tried sort array of comments manually @ backend , tried use aggregation, not able sort this. please.

presuming question model object in code , of course want sort "comments "date" createdat using .aggregate() use this:

question.aggregate([     // ideally match document want     { "$match": { "_id": docid } },      // unwind array contents     { "$unwind": "comments" },      // sort on array contents per document     { "$sort": { "_id": 1, "comments.createdat": 1 } },      // group structure     { "$group": {         "_id": "$_id",         "title": { "$first": "$title" },         "body": { "$first": "$body" },         "user": { "$first": "$user" },         "comments": { "$push": "$comments" },         "tags": { "$first": "$tags" },         "image": { "$first": "$image" },         "createdat": { "$first": "$createdat" }     }} ], function(err,results) {     // sorted results }); 

but overkill since not "aggregating" between documents. use javascript methods instead. such .sort():

quesion.findonebyid(docid,function(err,doc) {     if (err) throw (err);     var mydoc = doc.toobject();     mydoc.questions = mydoc.questions.sort(function(a,b) {         return a.createdat > b.createdat;     });    console.log( json.stringify( doc, undefined, 2 ) ); // intented nicely }); 

so whilst mongodb have "tools" on server, makes sense in client code when retrieve data unless need "aggregate" accross documents.

but both example usages have been given now.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -