2017年2月28日 星期二

[ MongoDB FAQ ] Find all objects in collection Java Mongodb3

Source From Here
Question
Below code finds the first document in a collection :
  1. package database;  
  2.   
  3. import com.mongodb.BasicDBObject;  
  4. import com.mongodb.BulkWriteOperation;  
  5. import com.mongodb.BulkWriteResult;  
  6. import com.mongodb.Cursor;  
  7. import com.mongodb.DB;  
  8. import com.mongodb.DBCollection;  
  9. import com.mongodb.DBCursor;  
  10. import com.mongodb.DBObject;  
  11. import com.mongodb.MongoClient;  
  12. import com.mongodb.ParallelScanOptions;  
  13. import com.mongodb.ServerAddress;  
  14.   
  15. import java.net.UnknownHostException;  
  16. import java.util.List;  
  17. import java.util.Set;  
  18.   
  19. import static java.util.concurrent.TimeUnit.SECONDS;  
  20.   
  21. // based on http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/  
  22.   
  23. public class Mongo {  
  24.   
  25.     public void getCon() {  
  26.         // or  
  27.         MongoClient mongoClient;  
  28.         try {  
  29.             mongoClient = new MongoClient("localhost"27017);  
  30.             DB db = mongoClient.getDB("mydb");  
  31.             DBCollection coll = db.getCollection("testCollection");  
  32.   
  33.             BasicDBObject doc = new BasicDBObject("name""MongoDB")  
  34.                     .append("type""database")  
  35.                     .append("count"1)  
  36.                     .append("info",  
  37.                             new BasicDBObject("x"203).append("y"102));  
  38.             coll.insert(doc);  
  39.   
  40.             coll.findOne();  
  41.         } catch (UnknownHostException e) {  
  42.             // TODO Auto-generated catch block  
  43.             e.printStackTrace();  
  44.         }  
  45.   
  46.     }  
  47. }  
There does not appear to be a findAll method. How to find all the documents in the collection testCollection ?

How-To
You have to use the DBCollection.find() method, which:
Select all documents in collection and get a cursor to the selected documents.

So, what you have to do, is:
  1. DBCursor cursor = coll.find();  
  2. while (cursor.hasNext()) {  
  3.    DBObject obj = cursor.next();  
  4.    //do your thing  
  5. }  


1 則留言:

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...