使用Java将值添加到MongoDB中的数组 [英] Adding values to an Array in MongoDB with Java
本文介绍了使用Java将值添加到MongoDB中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文档存储在mongo数据库的集合中.我希望能够添加到文档中已经存在的两个数组.
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) {
}
图片显示了第一种方法执行后,文档在MongoDB Compass中的外观
The picture shows what the document looks like in MongoDB Compass after the first method is executed
推荐答案
您的 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
数组 - 返回更新后的文档(此部分是可选的)
- Find the document having name=
listName
- Append the value of
newVocabTerm
to theterms
array - Append the the value of
newDefinition
to thedefinitions
array - Return the updated document (this part is optional)
这篇关于使用Java将值添加到MongoDB中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文