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

时间:2017-03-08 09:12:17

标签: java mongodb mongodb-java

@FormUrlEncoded
@POST("access.php")
Call<Object> authenticate(@Field("cod") String cod, @Field("usu") String usu, @Field("pas") String pas);

将结果表示为: {“_ id”:{“$ oid”:“58bfbcff1d30d8a8c1194328”},“ID”:1,“NAME”:“dgsdg”}

如何在没有objectid的情况下获取文档?

4 个答案:

答案 0 :(得分:4)

您可以使用projection

试试这个:

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

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

答案 1 :(得分:0)

我已经这样做了并且工作了:

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);
       }        

答案 2 :(得分:0)

首先你要导入这个,导入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);
   }        

答案 3 :(得分:-1)

您可以使用聚合框架来实现您的目标:

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

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