我是一个mongoDB菜鸟,我正在努力解决一个问题。我们假设我有以下结构:
{
"id": "1",
"type": 2,
"shops": ["1000","2000","3000"]
},
{
"id": "2",
"type": 2,
"shops": ["1000","4000","5000"]
}
如何删除每个等于1000的商店,以便生成的数据库记录为:
{
"id": "1",
"type": 2,
"shops": ["2000","3000"]
},
{
"id": "2",
"type": 2,
"shops": ["4000","5000"]
}
提前非常感谢!
答案 0 :(得分:2)
您可以使用pull operator执行如下操作:
db.shopCollection.update(
{ },
{ $pull: { "shops": { "idShop", 1000 } } },
{ multi: true }
)
假设shopCollection
为您的收藏品名称。
编辑 :要在java中使用相同的内容,您可以按照MongoDB Java pull中提到的答案进行操作。在java中,像这样:
Bson query = new org.bson.Document();
Bson fields = new org.bson.Document().append("shops", new org.bson.Document().append("$idShop",1000));
Bson update = new org.bson.Document("$pull",fields);
yourCollection.updateMany(query, update);
Edit2 :对于共享的更新JSON值,您可以将java代码更新为:
Bson filter = Filters.in("shops","1000");
Bson query = Filters.elemMatch("shops", filter);
Bson update = new org.bson.Document("$pull", filter);
campaignsCollection.updateMany(query, update);`