Yes, I want to pre-allocate specific number of elements in array, and keep number of elements static from there on. I was thinking of having element like "maxNumberOfObjects": 4
, but counting array elements in many places felt also pretty convenient, so defaulted to that.
Actually, document I would be updating, I know, so I have _id
of it at hand. So I can target specific document, and update empty object in arrayOfObjects
. Like you said more common way would be to use $push, this is kind of what I want to do, though instead of pushing new object in, updating first empty object, and ideally failing if there are no empty objects. If “nice” failing isn’t possible, I could first check that there is empty object before updating.
More traditional database/programming way I would most likely go finding [index]
in first query, then make another query which does update. However that update method seems to have arrayFilters
which I have feeling could get this done in one query. Didn’t find anyone trying to filter empty object, so trying to figure out how to write such query.
So I believe it would be something like:
db.collection.update(
{ "_id": "abc123" },
{ $set: { "objectName": "example2", "objectData": "newdata" } },
{
arrayFilters: $[ how_to_filter_empty_object ]
}
)
But I’m a bit lost what should be that actual filter there, and a bit unsure how correct is that $set line.
Do you catch my idea here, and have some pointers how to make that update as working one @Asya_Kamsky?
Also if you see some big drawbacks (other than being uncommon way to have empty objects), I’m eager to hear. My idea with this document structure has been that I need less queries and document structure contains meaningful information itself too.