Saurabh Yadav

How To Update Nested Array Of Object In MongoDB Collection!!

By Saurabh Yadav

Last updated cal_iconJune 12, 2022

So I assume the mongo queries are just like a veg curry. If we use the fresh vegetables (non-deprecated mongo crud operations method) and correct spices (mongo query operators), then the curry tastes good (correct result from mongo query); otherwise, we’ll miss something in the taste.Before discussing anything, first, we’ll know about the problem. Let’s see the image below,, which defines some percentage of the problem.

According to the image, we can understand that we want to increment the value of field count, which is currently present in visitors_uuid (array of object type), and the visitors_uuid is present under mostVisitedProfile (array of object type).

Problem Statement:-

Increase the value of visitors_uuid.count if mostVisitedProfile.uuid and visitors_uuid.uuid is same.

Take your time and make a mongo query for the above problem statement and before seeing the solution, put your queries in the comment box.

Solution:-

The solution query increments the count according to the problem statement condition.

Explanation:-GRF

It’s time to introduce the mongo operator responsible for the problem’s solution. It is positional filtered operator $[identifier]. In the above image, the $[inner] is the “positional filtered operator,” and inner is identifier.

The indentifier in filtered positional operator $[identifier] returns the array elements.

“In $[inner], the inner return the elements of the inner array one by one and we match those elements values in arrayFilters section of query.”

“So arrayFilters is an array that contains the objects, where object key is the identifier, and the value of that key is a condition that we need to execute in an inner array of Object. Same for the outer identifier.”

As shown in the above image, we get the element of visitors_uuid array in inner identifier and compare inner.uuid with request body visitors_uuid.

Conclusion:-

So if our request body is like 

{uuid: ‘mayank,’ visitors_uuid: ‘aakash’} then,

count value increase for “aakash” visitors_uuid.uuid only not for “saurabh” visitors_uuid.uuid .

References:-

https://www.mongodb.com/docs/manual/reference/operator/update/positional-filtered/

https://www.mongodb.com/docs/manual/release-notes/3.6/#std-label-3.6-arrayFilters

 

Get In Touch

How Can We Help ?

We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market

We specialize in full-stack software & web app development with a key focus on JavaScript, Kubernetes and Microservices
Your path to drive 360° value starts from here
Enhance your market & geographic reach by partnering with NodeXperts