0

I have a collection in mongo db which looks like this:

"notifications" : [
    {
        "type" : "Shout",
        "created" : ISODate("2014-04-24T13:37:02.678Z")
    },
    {
        "type" : "Shout",
        "created" : ISODate("2014-04-25T17:34:15.388Z")
    }
          ];

I just want to sort these notifications by created date and fetch them using mongo query but not able to do it. Can anybody help me.. Thanks..

2
  • Can you share your query ? Commented May 1, 2014 at 5:50
  • db.shouts.find({},{notifications:1}).sort({created: -1}).pretty() Commented May 1, 2014 at 5:56

1 Answer 1

2

You can probably use aggregation framework to sort your data based on date. Here is what I tried and its working fine.

db.shouts.aggregate([
  { "$unwind": "$notifications"}, 
  { "$sort": { "notifications.created": -1 }}, 
  { "$group": { "_id": "$_id", "notifications": { "$push": "$notifications" }}}
]);

and the result is:

 {
     "_id" : ObjectId("5361e2cfbf5e5bf862400210"),
     "notifications" : [
         {
             "type" : "Shout",
             "created" : ISODate("2014-04-25T17:34:15.388Z")
         },
         {
             "type" : "Shout",
             "created" : ISODate("2014-04-24T13:37:02.678Z")
         }
     ]
 }

hope it helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.