Adding values to an Array in MongoDB with Java

旧城冷巷雨未停 提交于 2021-02-08 07:52:05

问题


I have a document stored in a collection in a mongo database. I want to be able to add to two arrays that are already in the document.

Method for creating the document and arrays:

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);
}

Method where I want to add values into the array:

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


回答1:


Your addVocabToList() implementation will look something like this:

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));

That code will:

  • Find the document having name=listName
  • Append the value of newVocabTerm to the terms array
  • Append the the value of newDefinition to the definitions array
  • Return the updated document (this part is optional)


来源:https://stackoverflow.com/questions/45597271/adding-values-to-an-array-in-mongodb-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!