2016-12-18 43 views
0

我写了下面的代码基于链接 http://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/(见标题为“找到一个集合中的所有文件”):MongoDB的Java驱动程序:无法解析函数的toJSON()

import com.mongodb.MongoClient; 
import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoCursor; 
import com.mongodb.client.MongoDatabase; 

public class Main { 
    public static void main(String[] args) { 
     MongoClient mongoClient = new MongoClient(); 
     MongoDatabase database = mongoClient.getDatabase("test"); 
     MongoCollection collection = database.getCollection("test"); 
     MongoCursor cursor = collection.find().iterator(); 
     try { 
      while(cursor.hasNext()) { 
       System.out.println(cursor.next().toJson()); 
      } 
     } finally { 
      cursor.close(); 
     } 
    } 
} 

然而,我得到一个错误,该函数toJson()无法解析。你有什么想法我可以使这个代码工作?

回答

1

问题是缺少的类型。游标next方法返回collection的类型。下面的例子使用bson的Document类型。

import org.bson.Document; 

MongoDatabase database = mongoClient.getDatabase("test"); 
    MongoCollection<Document> collection = database.getCollection("test"); 
    MongoCursor<Document> cursor = collection.find().iterator(); 
    try { 
     while(cursor.hasNext()) { 
      System.out.println(cursor.next().toJson()); 
     } 
    } finally { 
     cursor.close(); 
    } 
+0

谢谢。但为什么在文档中缺少'?这是一个错误吗? – CrazySynthax

+1

我只是看着你提供的链接。看起来你引用的标题也有一个文档类型。 – Veeram

+0

谢谢。我可能错过了它。 – CrazySynthax

相关问题