Reputation: 60
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
Upvotes: 1
Views: 913
Reputation: 47865
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:
listName
newVocabTerm
to the terms
array newDefinition
to the definitions
arrayUpvotes: 3