2015-12-18 72 views
0

我希望檢索字符串數組或ArrayList(Java)中的「comment」字段的值。請參考圖片鏈接或指定了以下的MongoDB條目:如何使用java檢索mongodb中文檔字段的值列表?

{ 
"_id" : ObjectId("56740295f0a1e82444261cd4"), 
"Title" : "Campus", 
"Description" : "Nice", 
"City" : "Delhi", 
"Venue" : "Paschim Vihar", 
"Lab" : "Lab1", 
"Tags" : [ "people", " building" ], 
"UploadDate" : ISODate("2015-12-18T12:56:51.589Z"), 
"MediaCreationDate" : ISODate("0015-01-09T18:41:00Z"), 
"Likes" : 0, 
"Dislikes" : 0, 
"Video Hash" : "56740295f0a1e82444261cd4157", 
"Url" : "56740295f0a1e82444261cd4157", 
"comments" : [ "Hello Sir", "Hello World" ] 
} 

A document entry containing a list of values in the "comment field"

只是一個初學者。謝謝。

+0

不知道在什麼地方你需要幫助..讀取數據或將它們轉換。從數組轉換爲列表,看看這個:[從數組創建ArrayList](http://stackoverflow.com/questions/157944/create-arraylist-from-array) –

回答

0

首先,您需要在您的應用程序中添加mongodb驅動程序。 例如,對於行家:

 <dependency> 
     <groupId>org.mongodb</groupId> 
     <artifactId>mongo-java-driver</artifactId> 
     <version>3.1.0</version> 
    </dependency> 

然後,你需要像這樣寫代碼:

import static com.mongodb.client.model.Filters.*; 

public class FindTest { 
    public static void main(String[] args) { 
     //Connect to your mongodb instance 
     MongoClient client = new MongoClient(); 

     //Connect to your database 
     MongoDatabase db = client.getDatabase("try123"); 

     //Connect to your collection 
     MongoCollection<Document> collection = db.getCollection("one"); 

     //Execute query to database 
     List<Document> myDocs = collection.find(eq("Title", "Campus")).projection(Projections.include("comments")).into(new ArrayList<Document>()); 

     //Print result 
     for (Document d : myDocs) { 
      ArrayList<String> comments = (ArrayList<String>)d.get("comments"); 
      System.out.println(comments); 
     } 

     client.close(); 
    } 
} 
相關問題