如何在MongoDB中返回没有objectId的集合的文档?

问题描述:

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

给出结果为: { “_id”:{ “$ OID”: “58bfbcff1d30d8a8c1194328”}, “ID”:1, “名称”: “dgsdg”}如何在MongoDB中返回没有objectId的集合的文档?

如何获取文档没有目标?

+0

不知道与旧版本的Java客户端,但随着3.2+如果你定义在你的数据库文档你可以从文档数据库不包含ObjectId – nullpointer

+1

[如何使用Java驱动程序抑制mongodb中的列的可能的副本](http://stackoverflow.com/questions/40418885/how-to-suppress-a-column-in -mongodb-using-java-drivers) – Veeram

您可以使用projection

试试这个:

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

this MongoDB的文档,以了解更多。

+0

当我这样做时,它显示错误:类型不匹配:无法从对象[]转换为DBCursor – user7592766

+0

对不起,有一些错误,我已更新答案和链接,请有一个看看 –

+0

Iam得到错误“方法excludeId()未定义类型MongoData” – user7592766

您可以使用聚合框架来实现你想要什么:

db.getCollection( 'samplecollection')骨料([{$项目:{字段1:1,场2: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); 
    }