I have followed the online documentation to pull an item from an array and looked through the threads but I can’t find the solution to this problem. I’m trying to pull an item from a nested array, but it removes the nested arrays instead of just the single element. Can some one please explain this behaviour? and the potential solution. Thanks in advance.
I have modelled the same behaviour on the playground. Please see the link below. As you can see it returns an empty array. Please let me know what is wrong with my original code. Thanks again.
MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.
a.b searches for
field in subdocument-item if b is a string
that index array item if a number, for example a.0: "hello"
It follows that if we want to update a field with an array of documents we would end up with a.0.b for updating the first element (document) in the array a.0 with a field b
If we want to loop, we can specify the “magic index $” and replace a.0.b for a.$.b.
If we want to update not just one array item but all that match, we use a.$[].b: