❔ MongoDB Update nested elements
MongoDB question,
I'm trying to add a property to all of my existing documents.
The thing is, my document has a property called
Events
, this property is an array of Event
that might have multiple or 0 elements.
I want to update all the nested elements of that property if exists.
This is what I tried which doesn't work -
First part I'm making sure that events isn't an empty array.
Second part I'm adding to all the child elements the NewPropertyTest
and initializing it to false.
My attempt fails with matchedCount:0
.
Any tips?10 Replies
It looks like the query is incorrect. The $ne operator is used to match all documents where the field is not equal to a specified value. In your case, it should be checking if the field exists, not if it is not equal to an empty array.
This should match all documents that have the "Events" field and then add the "NewPropertyTest" property to all elements in the "Events" array and set its value to false.
Let me know if it helped @Ben
Your query will return all the documents.
As Events always exists (might be an empty array though).
What I did was -
Events:{$ne: []}
Which basically search for all the documents where events not equal to an empty array. meaning it has nested elementsThis query will return all documents where the Events field is an array with at least one element, but not an empty array.
Are you sure?
Iv'e just tested -
{ "Events": { $exists: true }
And it returns documents where Events is empty.Well just doing
{Events:{$ne: []}}
covers both 😅
Anyways the select query isn't the issue, its just when I run the update command with the set that it says -
matchedCount:0same result 😦
@Ben
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.