How to add new mail message to the mail field in an update?

Hello, my documents have multiple fields, one of them is the “mailReceived”. When a user sends a message to another user, I want to add that message to the existing messages stored under mailReceived. Although this is an insertion (new message), in the context of MongoDB, I have to do an update instead of post (I’m not adding a new document, just updating an existing document using $set). But for the mailReceived field, doing an update will replace all the existing mail messages with the new message, no, I don’t want to do that. I just want to add the new message to the existing messages stored in mailReceived. Is there a quick way to achieve this ? Right now, I have to read all the existing messages out and then store them as a list, then append the new message to the list, then save everything back in, it’s cumbersome. Hopefully, there’s a quick way to do it in Java. I appreciate any help, thanks so much!

Look at the $push update operator.

1 Like

Steeve,

Thanks a lot ! You are the man. I appreciate your assistance. It worked !

2 Likes

Hi Steeve,

During an update, to add a new message to the mailReceived field, I use $push. But now, instead of adding a new message, I want to delete an existing message from the mailReceived field while updating my document, is there something like $push for deletion? Could not find $delete/$remove from the MongoDB site. Thanks!

See the array update operations.

Thanks Steeve! (I just want to say thanks but it complains that my post has less than 20 characters :slight_smile: Hopefully, my submission goes through this time)

1 Like

I have to fight that do. I would write smaller post more often if I could. B-)

~~ /) ~~

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