如何 return MongoDB 中没有 objectId 的集合的文档?

How to return documents of a collection without objectId in MongoDB?

DB db = mongo.getDB("sample");
DBCollection table = db.getCollection("samplecollection");
DBCursor cursor2 = table.find();

给出的结果为: { “_id”:{ “$oid”:“58bfbcff1d30d8a8c1194328”},"ID":1,"NAME":"dgsdg"}

如何获取没有objectid的文档?

您可以使用 projection

试试这个:

DBCursor cursor2 = table.find().projection(excludeId()) 

阅读 this MongoDB 文档以了解更多信息。

你可以使用聚合框架来实现你想要的:

db.getCollection('samplecollection').aggregate([{$project: { field1:1 ,field2: 1......,'_id': 0} }])

https://docs.mongodb.com/manual/reference/operator/aggregation/project/

我已经完成并工作了:

MongoDatabase database = mongo.getDatabase("db");
     MongoCollection<org.bson.Document> contCol = database.getCollection("test");
     FindIterable<org.bson.Document> it = contCol.find().projection(excludeId());
     ArrayList<Document> docs = new ArrayList();


       for (org.bson.Document its : it) {
           System.out.println(its);
       }        

首先你要导入这个,导入com.mongodb.client.model.Projections;

那你也试试这个吧..

MongoClient client = new MongoClient("hostName");
MongoDatabase db = client.getDatabase("dbName");
MongoCollection<Document> collection = db.getCollection("collectionName");
collection.withWriteConcern(new WriteConcern(1));
/*   whatever field you dosn`t need.. you will run this following code, 

        FindIterable<Document> findDoc = collection.find().projection(new Document().append("_id",0));  //if you need mean, you put _id value is 1.

    */
FindIterable<Document> findDoc = collection.find().projection(Projections.excludeId()) ;
 for (Document doc : findDoc) {
       System.out.println(doc);
   }