本文介绍了使用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 the terms array
- Append the the value of newDefinition to the definitions array
- Return the updated document (this part is optional)
更多推荐
使用Java将值添加到MongoDB中的数组
发布评论