0

I've got a MongoDB nested array and am constantly adding and removing to the nested arrays inside. Sometimes this will leave lots of empty arrays just sitting around in their respective document. For example, take the image below. Lets say I remove index 0 and 1 from the play array. Considering it's now empty, I want play to be removed entirely from disabled_channels as soon as I complete .updateOne().

enter image description here

Is there a way to have MongoDB automatically remove an array field from a document after updating and the array is empty? I know you can do this with middleware but I've only ever seen this with Javascript, not Java :(

2 Answers 2

0

I would suggest you to run second query. AFAIK, there is no single query which automatically does this.

Reference

You can use $pull to remove null elements.

Sign up to request clarification or add additional context in comments.

Comments

0

You may have another query to remove empty arrays. But I don't recommend it. Because when you go deeper in query based methods, this will lead you NPE if its not correctly removed at all. This happens when you do long aggregation or use repositories against multiple collections. If you think removing an empty array is unwanted thing, don't do it.

3 Comments

Will it occupy any references in the memory? If we keep null elements in mongo.
Definitely yes, eg : hope you know $type. Null gets value 10. But I dont think null takes space much, may be only for key.
Let me know if you find anything, i will also refer and share with you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.