如何使用java检索mongodb中文档字段的值列表?

时间:2015-12-18 13:20:00

标签: java mongodb

我希望在String数组或ArrayList(Java)中检索“comment”字段的值。请参阅图像链接或指定的以下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"

刚开始。感谢。

1 个答案:

答案 0 :(得分:0)

首先,您需要在应用程序中添加mongodb驱动程序。 例如,对于maven:

     <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();
    }
}