I have a set of data that looks like this:
// Contained in a document named "Account"
{
"_id": abc-123,
"name": "MY-ACCOUNT",
"primary_contact_email": "[email protected]",
"projects": [
{
"projectId": xyz-456,
"name": "Test Project",
"description": "Description of project",
"credentials": [
{
"credentialId": efg-789,
"name": "Test Credential 1"
},
{
"credentialId": dbc-987,
"name": "Test Credential 2"
}
]
}
]
}
I would like to be able to delete a credential
based on the credentialId
. I’ve tried a few pieces of Java code to accomplish this, most recently this:
Query q = new Query();
q.addCriteria(Criteria.where("_id").is(accountId).and("projects.projectId").is(projectId));
Update u = new Update().pull("projects.$.credentials", Query.query(Criteria.where("credentialId").is(credentialId)));
var result = mongoTemplate.updateMulti(q, u, Account.class);
log.info(result.toString());
I feel like this is kind of close but am not sure why it’s not pulling/deleting the specific credential. I’m not receiving any errors with the above code, the result
just states AcknowledgedUpdateResult{matchedCount=0, modifiedCount=0, upsertedId=null}
.
This is my first time using MongoDB so I think the schema is correct, but am willing to change if necessary to accomplish this along with the other CRUD operations.
I know I could accomplish this is Java code using loops and indexes, but I thought that would defeat the purpose of Mongos performance.
I’m using the Spring Boot starter: org.springframework.boot:spring-boot-starter-data-mongodb
which pulls in the latest 5.1 driver.