Is it possible to set a field in the last element in an array? I tried a couple of options but sadly did not work for me. (I’m using NodeJS)
I have added an example document at bottom in which chat is an array field with objects. Each object has question and answer fields. I want to update the document by setting answer in the last element, where answer will have the following shape:
It sounds like you’re actually trying to add a new element to the array rather than just updating the last element. If that’s the case, the correct approach would be to use the $push operator. This is the easiest way to append a new object to the end of an array in MongoDB.
const result = await collection.updateOne(
{ _id: documentId },
{ $push: { chat: newChat } } // Adds the new object to the end of the 'chat' array
);
$push: Adds a new object to the end of the chat array.
What I understand is that you want the chat array to become:
That is you want the 2nd element, that is chat[ 1 ], to the answer object because the question object is present and the answer is not.
If that is the case, look at this playground. It uses the $ operator to update the element specified by $elemMatch to specify an element that has a question but no answer.
It will not be necessarily the last, in fact it is the first that matches the $elemMatch.