Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
Java MongoClient to add a new embedded document

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"
    }]
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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/

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!