2017-02-25 50 views
0

我有一個這樣的文件:插件組到MongoDB中現有的文檔使用Java

{ 
    "_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"] 
} 

我嘗試了一些方法,但結束了很多錯誤。我是新來的。請誰能告訴我如何做到這一點?

回答

2

你可以嘗試下面的東西。您可以根據您的過濾器調整查詢。

使用$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)); 
+0

太謝謝你了! –

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); 
相關問題