Updated Nested Array Value in Java

This seems so simple, and I was able to do it in Python, no problem, but in Java, no one seems to know.

I have this document:

{
    _id: ObjectId("6511bad731f6775711b4ee51"),
    emp_no: 211,
    last_name: 'Susan',
    first_name: 'Fillingnough',
    hired_on: ISODate("2023-09-25T16:52:39.774Z"),
    phoneNumbers: [
      { type: 'Home', number: '111-000-2222' },
      { type: 'Cell', number: '222-111-3333' }
    ],
    married: 'n'
  }

In Java, I would like to update the Home phoneNumber to something else. In Python, I did it this way:

theresult = collection.update_one({"emp_no" : 211 , "phoneNumbers.type":"Home"} , {"$set": {"phoneNumbers.$.number": "647-298-7194"}})

How could one do this in Java and C/C++?

Thanks all!

Figured it out. And No-SQL is a benefit here?

Document empDocument = new Document();
empDocument.append("emp_no", 211L);
empDocument.append("phoneNumbers.type", "Home");
tempDocument = new Document();
Document tempDocument.append("$set", new Document("phoneNumbers.$.number", "647-298-7194"));
theUpdateResult = collection.updateOne(empDocument, tempDocument);
if (theUpdateResult.getModifiedCount() == 0) {	
	System.out.println("Error updating the employee details home phone number");
}//if
else {
	System.out.println("Employee home phone number details document successfully updated");
}//else
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.