-1

I have a collection of queries,data stored on the records look like the following.i want to sort according to the id or the date inside the array in descending orders

[
    {
        "_id": "5e71fa3ab004192b349e4a06",
        "QUERIES": [
            {
                "_id": "5e71fa3ab004192b349e4a07",
                "QUERY": "1",
                "USER_ID": "5e6f1c5b8451307f782d0994",
                "USER_NAME": "a2",
                "createdAt": "2020-03-18T10:38:50.247Z"
            },
            {
                "_id": "5e71fa46b004192b349e4a08",
                "QUERY": "2",
                "USER_ID": "5e6f1c5b8451307f782d0994",
                "USER_NAME": "a1",
                "createdAt": "2020-03-18T10:39:02.451Z"
            }
        ],
        "TICKET_ID": "5e70f4fa47df9479502f7937"
]

Expected output

[
        {
            "_id": "5e71fa3ab004192b349e4a06",
            "QUERIES": [

                {
                    "_id": "5e71fa46b004192b349e4a08",
                    "QUERY": "2",
                    "USER_ID": "5e6f1c5b8451307f782d0994",
                    "USER_NAME": "a1",
                    "createdAt": "2020-03-18T10:39:02.451Z"
                },
                {
                    "_id": "5e71fa3ab004192b349e4a07",
                    "QUERY": "1",
                    "USER_ID": "5e6f1c5b8451307f782d0994",
                    "USER_NAME": "a2",
                    "createdAt": "2020-03-18T10:38:50.247Z"
                }
            ],
            "TICKET_ID": "5e70f4fa47df9479502f7937"
    ]
5
  • Are you using MongoDB directly or something like Mongoose? Commented Mar 18, 2020 at 11:23
  • See here: stackoverflow.com/questions/54366459/…. is that what you want? Commented Mar 18, 2020 at 11:27
  • using mongoose for handling MongoDB Operations Commented Mar 18, 2020 at 11:37
  • the question I have pointed you out to is what you want? Commented Mar 18, 2020 at 11:45
  • I want mongoDB query code for getting the expected output,which is already mentioned on the question Commented Mar 18, 2020 at 12:13

1 Answer 1

0

Use this one:

db.collection.aggregate([
   { $unwind: "$QUERIES" },
   { $sort: { "QUERIES.createdAt": -1 } },
   {
      $group: {
         _id: { _id: "$_id", TICKET_ID: "$TICKET_ID" },
         QUERIES: { $push: "$QUERIES" }
      }
   },
   { $replaceRoot: { newRoot: { $mergeObjects: ["$$ROOT", "$_id"] } } }
])

Mongo playground

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

1 Comment

Thank you @Wernfried Domscheit

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.