Consider the following MongoDB document:
SomeObject {
nested_objects_ids : [
ObjectId( "1..." ),
ObjectId( "2..." ),
...
ObjectId( "N..." )
]
}
The length of nested_object_ids is not limited.
Is there an elegant way to keep the nested_object_ids array sorted after pushing arbitrary values (i.e. ObjectIds)?
Thank you!
Unfortunately, there is nothing I would consider “elegant”.
The
$pushcommand does not work here. Your only option is to pull the entire sub-array into the client and then re-write it with a$set.Honestly, when it comes to dealing with “arrays of objects”, MongoDB has limited functionality. You can update with
$push,$pulland you can index on an object field, but that’s about it.It’s difficult to update a specific sub-object. And querying doesn’t return the sub-object, but instead returns the whole document. You could filter it down to returning
nested_object_ids, but you always get the whole set there.A question for you: why do the nested objects need to be sorted?