2017-08-09 49 views
1

我有一個文檔存儲在mongo數據庫的集合中。我想能夠添加到已經在文檔中的兩個數組。使用Java將值添加到MongoDB中的數組

用於創建文檔和數組

方法:

public void addNewListName(String listName) { 

    MongoCollection<Document> collection = database.getCollection("lists"); 

    ArrayList<DBObject> array = new ArrayList<DBObject>(); 
    Document list = new Document ("name", listName) 
      .append("terms", array) 
      .append("definitions", array); 
    collection.insertOne(list); 
} 

方法,我想值添加到陣列中:

public void addVocabToList(String listName, String newVocabTerm, String newDefinition) { 

} 

The picture shows what the document looks like in MongoDB Compass after the first method is executed

圖爲該文件是什麼樣子在MongoDB Compass中執行第一種方法後

回答

1

addVocabToList()實施,將是這個樣子:

MongoCollection<Document> collection = database.getCollection("lists"); 

Document updatedDocument = collection.findOneAndUpdate(
    Filters.eq("name", listName), 
    new Document("$push", 
     new BasicDBObject("terms", new BsonString(newVocabTerm)) 
      .append("definitions", new BsonString(newDefinition))), 
     new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)); 

該代碼將:

  • 找到一個具有名稱文件= listName
  • newVocabTerm價值附加到terms陣列
  • newDefinition的值附加到definitions陣列
  • 返回更新的文件(此部分是可選的)
+0

完美地工作。非常感謝! – KobiF