Unable to sort embedded array of subdocuments

I have an endpoint that updates products and among other things that use $set and $unset it also optionally uses $push whenever a product delivery status is updated. I have found the following documentation page that shows how to use $sort during update: https://www.mongodb.com/docs/manual/reference/operator/update/sort/#up._S_sort

Unfortunately, I was not able to sort the statusJournal array of subdocuments inside my Product document.

The statusJournal array is structured as follows:

    "statusJournal" : [
        {
            "status" : "PRODUCT_CREATED",
            "date" : ISODate("2023-08-02T13:27:37.415+0000"),
            "description" : "test",
        },
        {
            "status" : "PRODUCT_OUT_FOR_DELIVERY",
            "date" : ISODate("2023-08-30T22:00:00.000+0000"),
            "description" : "test2",
        },
        {
            "status" : "PRODUCT_DELIVERED",
            "date" : ISODate("2023-08-03T22:00:00.000+0000"),
        }
    ],

The code that performs the potential $push (among other things described above) looks like this:

    const patchedProduct = await updateProduct(
        {productId: req.params.productId},
        {$set: patchProduct, $unset: patchProductUnsetQuery,
            $push: {statusJournal: {$each: [statusJournalEntry]}, $sort: {date: 1}}});

As you can see, I am attempting to (re)sort the array of subdocuments based on the date field value whenever a new status object is pushed, however it does not work, and a new pushed subdocument is simply placed at the end of the array. As you can see in the statusJournal example provided above, after pushing the PRODUCT_DELIVERED subdocument it appears below the PRODUCT_OUT_FOR_DELIVERY subdocument, even though the date is lesser.

What am I doing wrong?

Thanks

1 Like

OR: Does it only sort the input elements and don’t touch the elements in the array that already exist?

According to the documentation you share you are using the syntax wrong by having the { and } and the wrong place. I think it should be

$push: { statusJournal: { $each: [ statusJournalEntry ] , $sort: {date: 1} }
3 Likes

Thank you very much @steevej. Nice catch

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.