Ich bin neu in MongoDB. Ich benutze MongoDB mit Java-Treiber-3.2.2. Früher habe ich den folgenden Code benutzt, um das Ergebnis aus der Datenbank zu holen.Bessere Möglichkeit, das Ergebnis aus der MongoDB mit Java-Treiber zu holen
MongoClient mongoClient = new MongoClient("localhost", 27017);
@SuppressWarnings("deprecation")
DB deviceBaseDB = mongoClient.getDB("test");
DBCollection deviceBaseCollection = deviceBaseDB.getCollection("myFirstCollection");
List<String> list = new ArrayList<String>();
DBCursor cursor = deviceBaseCollection.find(queryObject, projection)
.sort(sortingCriteriea).limit(10);
while (cursor.hasNext()) {
list.add(cursor.next().toString());
}
But in the above code mongoClient.getDB() call is depricated. So I am trying to use New API() from MongoDB like below.
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("myFirstCollection");
// First approach
List<Document> listDocs = collection.find().projection(projection)
.sort(new BasicDBObject("likes", -1)).into(new ArrayList<Document>());
List<String> strList1 = new ArrayList<String>();
for(Document doc : listDocs) {
strList1.add(doc.toJson());
}
System.out.println("List of json files strList1:: " + strList1);
// Second Approach
FindIterable<Document> iterableDocsWithFilter_SortWithProject = collection.find(
new BasicDBObject("title", "New MongoDB Learning")).projection(projection)
.sort(new BasicDBObject("likes", -1));
Iterator<Document> iterator = iterableDocsWithFilter_SortWithProject.iterator();
List<String> strList2 = new ArrayList<String>();
while (iterator.hasNext()) {
strList2.add(iterator.next().toJson());
}
System.out.println("List of json files strList2:: " + strList2);
// Third Approach
MongoCursor<Document> mongoCursor = (MongoCursor<Document>) collection.find(
new BasicDBObject("title", "New MongoDB Learning")).projection(projection)
.sort(new BasicDBObject("likes", -1));
List<String> strList3 = new ArrayList<String>();
while(mongoCursor.hasNext()) {
strList3.add(mongoCursor.next().toJson());
}
System.out.println("List of json files strList3:: " + strList3);
Meine Abfragen sind unter:
1) Werden neue API (document.toJson()), um die Leistung zu erhöhen, wie alt depricated API vergleichen (mit toString (Dbcursor))? 2) Ich habe 3 Möglichkeiten gefunden, das Ergebnis aus der MongoDB mit der neuen API zu holen, welche ist besser unter allen 3 Ansätzen?