使用Java将值添加到MongoDB中的数组

编程入门 行业动态 更新时间:2024-10-15 06:14:05
本文介绍了使用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中的数组

本文发布于:2023-11-22 14:29:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Java   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!