Updating subobject string field in Java using $Concat and UpdateOne

Question:
What is the sample value in the database that needs to be formatted?
The sample value in the database is “one-two-three.js”.
How can the hyphens in the value be replaced with spaces after splitting the field using aggregate?
You can use the “replaceAll(“-“, ” “)” method.
Solution:
You can try using the “your tried code” with the “name” and retrieve the first element using “get first element using”.
Then, iterate through the array after converting it from a string using “to iterate loop of” and concatenate the string with spaces.
Finally, return the value, which will have an extra space at the first position. Use “will remove that first position space” to remove that space.
Playground:
You are updating a document in the array field and using “which requires an aggregation pipeline” at the same time.


Question:

I’m utilizing mongo-
java-driver
for
mongodb connection
and would like to modify a specific field within a subobject of the document.

Record:

{
    "_id": "61866c32d11c9aefb01125f7",
    "number": 1900,
    "oms": "ters",
    "data": [
        {
            "empCode": "EMP2",
            "firstname": "vivek",
            "lastname": "bdh",
            "age": 30
        },
        {
            "empCode": "EMP3",
            "firstname": "ravi",
            "lastname": "sh",
            "age": 30
        }
    ],
    "volgnummer": 1
}

The intention was to modify the surname for empCode “EMP2”.

Below is the code snippet I have written to execute the operation.

public class FixDataApp {
    public static void main(String[] args) throws IOException {
        MongoCollection collection = MongoConfig.getCollection(args[0], args[1], "myCollection");
        
        BasicDBObject concat = new BasicDBObject();
        concat.put("$concat",  Arrays.asList(
                new BsonString("data.$.lastname"),
                new BsonString(" TestAppendStr")));
        BasicDBObject updateFields = new BasicDBObject();
        updateFields.append( "data.$.lastname", concat);
        BasicDBObject command = new BasicDBObject();
        command.put("$set", updateFields);
        UpdateResult result = collection.updateOne(
                Filters.and(
                        Filters.eq("_id", "61866c32d11c9aefb01125f7"),
                        Filters.eq("data.empCode", "EMP2")
                ),
                command
        );
        System.out.println("Record updated successfully " + result.getModifiedCount());
    }
}

Upon executing the aforementioned application, the following error is encountered…

Exception in thread "main" com.mongodb.MongoWriteException: The dollar ($) prefixed field '$concat' in 'data.0.lastname.$concat' is not valid for storage.
    at com.mongodb.client.internal.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:1060)
    at com.mongodb.client.internal.MongoCollectionImpl.executeUpdate(MongoCollectionImpl.java:1037)
    at com.mongodb.client.internal.MongoCollectionImpl.updateOne(MongoCollectionImpl.java:622)
    at com.mongodb.client.internal.MongoCollectionImpl.updateOne(MongoCollectionImpl.java:617)
    at common.FixDataApp.main(FixDataApp.java:30)

I need assistance in using the $concat and update method to update a specific field. Thank you.


Solution:

A bit complex
MongoDB update
query.

While making updates to a document in the
array field
section, you need to simultaneously utilize

$concat

, which necessitates an aggregation pipeline.

When you don’t have the

$concat

(aggregation pipeline), you have the option to utilize

arrayFilters

and

$[elem]

, which are more straightforward and convenient for modifying the desired
document field
in the
nested array
.


The main points in the below query:

– For every document in the array field, iterate and make updates.

– If the requirement is met, the field

lastname

will be populated with the value from

$concat

. Otherwise, it will be updated with the original value.

Combine the initial document (

$mergeObjects

) with the updated field (

$emp

) to create a merged document (

lastname

).

db.collection.update({
  "_id": "61866c32d11c9aefb01125f7",
  "data.empCode": "EMP2"
},
[
  {
    $set: {
      "data": {
        "$map": {
          "input": "$data",
          "as": "emp",
          "in": {
            $mergeObjects: [
              "$$emp",
              {
                "lastname": {
                  $cond: {
                    if: {
                      $eq: [
                        "$$emp.empCode",
                        "EMP2"
                      ]
                    },
                    then: {
                      $concat: [
                        "$$emp.lastname",
                        " TestAppendStr"
                      ]
                    },
                    else: "$$emp.lastname"
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground

Frequently Asked Questions