I wish to retrieve the values of "comment" field in a String array or ArrayList (Java). Please refer to the image link or the following mongodb entry specified:
{
"_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" ]
}
Just a beginner. Thanks.
Firstly, you need to add in your application mongodb driver. For example, for maven:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.1.0</version>
</dependency>
Then you need to write code like this:
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.