我有一个这样的文档:
{
"_id" : ObjectId("58b1404d002d2b1a481b8ddf"),
"firstName" : "ABC",
"lastName" : "XYZ"
}
我有一个名为主题的列表:
List<String> topics = new ArrayList<String>();
topics.add("Business");
topics.add("Technology");
topics.add("Sports");
topics.add("Career");
现在,我想像这样更新我的文档:
{
"_id" : ObjectId("58b1404d002d2b1a481b8ddf"),
"firstName" : "ABC",
"lastName" : "XYZ",
"readAbout" : ["Business", "Technology", "Sports", "Career"]
}
我尝试了一些方法,但最终出现了很多错误。我是新来的。请问有人可以建议我如何做到这一点吗?
最佳答案
您可以尝试如下所示的操作。您可以根据您的过滤器调整查询。
使用 $push
和 $each
将每个元素追加到数组中。
MongoClient client= new MongoClient();
MongoDatabase db = client.getDatabase("dbname");
MongoCollection col = db.getCollection("dbcollection");
List<String> topics = new ArrayList<String>();
topics.add("Business");
topics.add("Technology");
topics.add("Sports");
topics.add("Career");
col.findOneAndUpdate(Filters.eq("_id", new ObjectId("58b1404d002d2b1a481b8ddf")), Updates.pushEach("readAbout", topics));
关于java - 使用 Java 将数组插入 mongoDB 中的现有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42453846/