Querying nested objects

Dear Mongo Community,

I’m look back to 25 years of relational database and are now diving into document-based-mongodb. And I have a question how to model the following case:

Assuming I have I forum with posts:

 "UserName": "The only one user",
 "Posts": [
     "Date": "01.01.2023 23:40:02",
     "Type": 3
     "Message": "Hello world"
     "Date": "02.01.2023 22:42:02",
     "Type": 2
     "Message": "Hello earth"

Imaging there are a lot of messages per user and a lot of user.
If I want to display the last 20 messages across all users what would the query look like?
Or do i have to reorganize the posts into a seperate collection?

Thank you, for your input.

Please do not store your date as string.

Dates as strings take more space, are slower to compare and in your specific format cannot be sorted.

You could use a projection that uses something:

{ "Posts" : { "$slice" : [ -1 , 20 ] }
1 Like