V
V
Vladimir2017-05-16 10:50:30
JavaScript
Vladimir, 2017-05-16 10:50:30

How to sort an array of objects by date in MongoDB?

I have a collection with the following schema:

var project = new Schema({
head:{
    head_task: String,
    userID: String
},
access_users: {
    type : Array ,
    "default" : []},
context_task: [{
            from_name: String,
            status: Boolean,
            task: String,
            created_task: {
                type: Date,
                default: Date.now()
             }
        }],
created: {
        type: Date,
        default: Date.now
    }});

Tell me how to get a document sorted by the context_task.created_task field in descending order. As far as I understand, you need to use aggregation, the next query is db.tasks.aggregate({$match :{"_id":ObjectId("590e2d7d4d4a5e0b647d0835")}}, {$sort: {"context_task.created_task": -1}}). pretty(); outputs the document in the normal order, sorting does not work. Or it all needs to be done already on the client?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2017-05-16
@lega

Or it all needs to be done already on the client?
Yes, sorting is for documents, not their content.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question