我插入了一个具有这种结构的文档
{
"_id" : ObjectId("5708bf40a86e6f5bd1f45354"),
"companyId" : ObjectId("5708bed6a86e6f5bd1f4534f"),
"descriptions" : [
{ "id" : ObjectId("5708bf40a86e6f5bd1f45351"), "description" : "test" },
{ "id" : ObjectId("5708bf40a86e6f5bd1f45352"), "description" : "test1" },
{ "id" : ObjectId("5708bf40a86e6f5bd1f45353"), "description" : "test2" }
]
}
现在我尝试通过删除与某些条件匹配的对象来修改数组 - 在这种情况下,我需要删除具有特定 id
的对象.
这是我到目前为止所做的,但没有成功
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", "")));
}
这是setCollection
方法
private MongoCollection<Document> setCollection(final String collectionName){
return db.getCollection(collectionName);
}
updateOne
什么也不做。我知道我的查询看起来很奇怪,但我无法理解发生了什么以及如何从数组中删除文档。我也尝试过 $pull
但我一点运气都没有。
我知道我在这里遗漏了一些小而非常基本的东西,但作为 MongoDB 初学者,我无法发现它。
你能帮我推一下吗?
最佳答案
您可以尝试更换
new Document("$unset", new Document("descriptions.description", ""))
经过
new Document("$pull", new Document("descriptions.id", new ObjectId(descriptionId)))
。
请参阅文档 pull operator .
关于java - 如何从数组中删除文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36514765/