I have inserted a document with this structure
{
"_id" : ObjectId("5708bf40a86e6f5bd1f45354"),
"companyId" : ObjectId("5708bed6a86e6f5bd1f4534f"),
"descriptions" : [
{ "id" : ObjectId("5708bf40a86e6f5bd1f45351"), "description" : "test" },
{ "id" : ObjectId("5708bf40a86e6f5bd1f45352"), "description" : "test1" },
{ "id" : ObjectId("5708bf40a86e6f5bd1f45353"), "description" : "test2" }
]
}
and now I'm trying to modify the array by removing an object which is matching some criteria - in this case I need to remove the object with a specific id
.
Here is what I'm doing so far, without any success
public void deleteCustomField(final String descriptionId, final ObjectId companyId){
MongoCollection<Document> collection = setCollection(CUSTOM_FIELDS_COLLECTION);
collection.updateOne(and(eq("companyId", companyId), eq("descriptions.id", new ObjectId(descriptionId))), new Document("$unset", new Document("descriptions.description", "")));
}
This is the setCollection
method
private MongoCollection<Document> setCollection(final String collectionName){
return db.getCollection(collectionName);
}
The updateOne
does nothing at all. I know that my query is looking strange, but I can't understand what is going on and how to remove the document from the array. I also tried with $pull
but I had no luck at all.
I know that I'm missing something small and really basic here, but as a MongoDB beginner, I'm not able to spot it.
Can you give me a push?
You may try to replace
new Document("$unset", new Document("descriptions.description", ""))
by
new Document("$pull", new Document("descriptions.id", new ObjectId(descriptionId)))
.
See the doc for the pull operator.