2017-08-21 28 views
2

我是一個mongoDB noob,我很苦惱與查詢。假設我有以下結構:MongoDB的Java - 如何刪除數組的元素等於某些值?

{ 
    "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

更新JSON' 「商店」: 0:4000 1:5000 ]'對我來說似乎不正確。該列表中應包含一些對象以包含這些鍵和值。 – nullpointer

回答

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);` 
+1

非常感謝您回答如此之快。我通過調用getCollection(「shops」)獲得集合,但找不到「update」方法,只有updateOne和updateMany。 – Poider12

+1

@ Poider12請使用您用來訪問該集合的Java代碼更新該問題。還要注意,我共享的查詢是用於mongo shell而不是Java。你可以用java中的updateMany來更新文檔列表。 – nullpointer

+0

Bson query = new Document(); Bson fields = new Document()。append(「spots」,new Document()。append(「$ elemMatch」,1000)); Bson update = new Document(「$ pull」,fields); campaignsCollection.updateMany(查詢,更新);應該是這樣的? – Poider12

相關問題