MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Updating values in a nested array using java streams

Dear All,

I have an array with multiple objects within and I want to update the value of a particular field in all the objects within the array using java streams.
Can you guide me on the same ?

Thanks,
Jay

To update all sub-documents (or objects) with an array - you use the all positional operator $[ ] for specifying the update.

I am not sure using Java Streams API will be of any use in this case; but, you can be little more detailed about why you want to use Streams API. What is it that you think needs the usage of Streams in this case (perhaps, you have special case)? Please give an example.

MongoDB Java driver has specific API methods to perform the update using the all positional operator. With the Java driver API calls the update on a document (and all the objects within the array) happens atomically.

1 Like

Thanks Prasad. I will use the MongoDB Java Driver and update.

In the meanwhile, I also have a situation, I have to perform some masking strategy on multiple DB’s for specific fields within the collections. There is search criteria that I need to use.
Do I have to fetch each matching document and update one by one ? Because, the masking strategy differs for each of the fields.

Thanks in advance for your help !!
Jay.

Do I have to fetch each matching document and update one by one ?

An update to a document is atomic. An update for multiple documents can be batched together and submitted to be performed on the database server as a single operation; but, still each document is updated individually.

In the meanwhile, I also have a situation, I have to perform some masking strategy on multiple DB’s for specific fields within the collections.

I don’t know the masking startegey you have in place or you are intending to implement (something like Field Level Redaction). $redact is an Aggregation pipeline stage.

Note that an update operation can be combined with an aggregation pipeline.

1 Like

Just to give you some details -
I have multiple DB’s - DB1, DB2 … and multiple collections within.
Now, there are few fields/columns that are identified within each of the collections that I need to mask/obfuscate.
Each field has a different masking algorithm (first 4 and last four as XXXX, or full masking - XXXXXXX and for date - mask everything to XXXX except for year).
So, I have to fetch the required documents (using the search criteria), then based on the fields value in that document, perform the masking logic and update back the document into DB.
This I have to repeat for every document, in all the collections and DB.
I am using Java Mongodb Driver as well as Java Reactive Streams driver for this.