mongodb - how to project last element of an array after an update

Viewed 244

So I have the following query:

ListModel
    .findOneAndUpdate(
        {
            _id: list_id
        },
        {   
            $push: {
                "items": {
                    details: the_template
                }
            }
        },
        {
            new: true,
            projection: {
                items: 1
            }
        }
    )

So, this returns me the array of the updated document, but how would I get only the last element inserted?

1 Answers

You can use of $slice, in your case :


ListModel
    .findOneAndUpdate(
        {
            _id: list_id,
        },
        {   
            $push: {
                items: {
                    details: the_template,
                },
            },
        },
        {
            new: true,

            projection: {
               items: {
                  $slice: -1,
               },
            },
        },
    );
Related