A consultant that knows MongoDB or a MongoDB employee that you hired as a consultant. As a independent consultant myself my recommendation is to not blindly listen to consultants. If the recommendation of not using array is from a MongoDB employee I would like MongoDB staff in this forum to comment on the avoid array recommendation.
I just made 2 simple collections, one using the map way and the other using the array way with the 2 documents from my previous post and I got:
db.as_array.stats().size
315
db.as_object.stats().size
361
Yes 46 bytes for 2 ‘activity’ is not that much. But to reach the 16M limit you must have a lot of ‘activity’. End of my argument about size.
The update source of your post is not that simple. With array you could easily implement the bucket pattern using $size in the query part to limit the array size completely avoiding the need to handle a 16M error. With the bucket pattern you can
Are you sure about
Are those dynamic keys sorted/indexed? I do not think they are. With an array you could easily index activities._id and make query an order of magnitude faster.
I am curious about how you do queries like Which user did txtNameActivity:testActivity2 or What activity was done on a give tstActivity date?
The consultant should have shown you.
For example
key = "63ff26237d68b622e28852b3"
{ "$unset" : [ "activities." + key ] }
would be
key = "63ff26237d68b622e28852b3"
{ "$pull" : { "activities" : { "_id" : new ObjectId( key ) } } }
To avoid duplicates you would
activity = {
"_id": { "$oid": "63ff26237d68b622e28852b3" },
"tstActivity": { "$date": "2023-03-01T11:17:06.000Z" },
"txtNameActivity": "testActivity1"
}
... { "$addToSet" : { "activities" : activity } }
My point is that we can do with dynamic keys can be done with arrays.
With dynamic keys I have to idea how this could be done without $objectToArray like you do.
You could use MongoCollection<Document> rather than MongoCollection<Activities> to aggregate in order to get the $min.