2

I have a collection like :

{"x":{"y":[
{"date":ISODate("2014-07-24T21:00:00.000Z"),"k":5 },
{"date":ISODate("2014-07-22T21:00:00.000Z"),"k":6 } ] }}

I want to sort y array according to "date" parameter.So i made the code like this :

query.with(new Sort(Sort.Direction.ASC, "y.date"));

I want to output like this:

{"x":{"y":[
    {"date":ISODate("2014-07-22T21:00:00.000Z"),"k":5 },
    {"date":ISODate("2014-07-24T21:00:00.000Z"),"k":6 } ] }}

How can i make the output like this ? is the code that i made ,it is ok ?

1 Answer 1

2

Using aggregation, your query should look like this, since you want to sort elements of 'y' based on 'date' in ascending order.

db.test.aggregate([ {$unwind: "$y"},
{$sort: {"y.date":1}},
{$group: {_id:"$_id", y: {$push:"$y"}}} ]);

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

2 Comments

thanx @vmr.But "unwind" already split the documents and every document has one y...sorting has no mean in like this situation.
The order will be maintained during grouping per _id, so it should reach your target.

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.