2

I have a below data type in mongodb

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men"
}

Since the above data is already an existing data, Now using the MongoClient I want to insert the new embedded document based on the _id as below

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men",
    "subCategory" : [{
        "name" : "This is name update",
        "description" : "This is update"
    }]
}

Once, the array has been inserted, Again I have the requirement to add another item to the array, something like below

{
    "_id" : ObjectId("60007b3abc54b5305e9f5601"),
    "description" : "Mens",
    "name" : "Men",
    "subCategory" : [{
        "name" : "This is name update",
        "description" : "This is update"
    },
{
        "name" : "This is name update",
        "description" : "This is update"
    }]
}
San Jaisy
  • 15,327
  • 34
  • 171
  • 290

1 Answers1

1

Code to update :

import static com.mongodb.client.model.Filters.eq;

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("some_db_name");
MongoCollection<Document> collection = database.getCollection("some_database");
Document document = collection.find(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")))
                              .first();

Object object = document.get("subCategory");

List<Document> documents = new ArrayList<>();

if(object != null) {
  documents = (List<Document>) object;
}

documents.add(new Document("name", "This is name update")
              .append("description", "This is update")); 

document.append("subCategory", documents);

collection.updateOne(eq("_id", new ObjectId("60007b3abc54b5305e9f5601")), 
         new Document("$set", new Document("subCategory", documents)));

 

Read docs : https://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/

Anish B.
  • 9,111
  • 3
  • 21
  • 41