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

193
Views
Java MongoClient para agregar un nuevo documento incrustado

Tengo un tipo de datos a continuación en mongodb

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

Dado que los datos anteriores ya son datos existentes, ahora usando MongoClient quiero insertar el nuevo documento incrustado basado en el _id como se muestra a continuación

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

Una vez que se insertó la matriz, nuevamente tengo el requisito de agregar otro elemento a la matriz, algo como a continuación

 { "_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

Código para actualizar:

 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)));

Leer documentos: 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!