我有这样的文件:
{
"_id" : ObjectId("58b1404d002d2b1a481b8ddf"),
"firstName" : "ABC",
"lastName" : "XYZ"
}
我有一个名为Topics的列表:
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"]
}
我尝试了一些方法,但结果却出现了很多错误。我是新手。请有人建议我怎么做吗?
答案 0 :(得分:3)
您可以尝试以下内容。您可以根据过滤器调整查询。
将$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));
答案 1 :(得分:0)
使用此代码更新单个文档 代码:
MongoClient client = new MongoClient("localhost",27017);
MongoDatabase db = client.getDatabase("count");
MongoCollection<Document> collection = db.getCollection("test");
Document query = new Document();
query.append("firstName" , "ABC");
List<String> topics = new ArrayList<String>();
topics.add("Business");
topics.add("Technology");
topics.add("Sports");
topics.add("Career");
Document setData = new Document();
setData.append("readAbout", topics);
Document update = new Document();
update.append("$set", setData);
//To update single Document
collection.updateOne(query, update);