【问题标题】:How to return documents of a collection without objectId in MongoDB?如何在 MongoDB 中返回没有 objectId 的集合的文档?
【发布时间】:2017-03-08 09:12:17
【问题描述】:
DB db = mongo.getDB("sample");
DBCollection table = db.getCollection("samplecollection");
DBCursor cursor2 = table.find();

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

如何获取没有objectid的文档?

【问题讨论】:

标签: java mongodb mongodb-java


【解决方案1】:

您可以为此使用projection

试试这个:

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

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

【讨论】:

  • 当我这样做时显示错误:类型不匹配:无法从 Object[] 转换为 DBCursor
  • 对不起,有错误,我已经更新了答案和链接,请看一下
  • 我收到错误“MongoData 类型的 excludeId() 方法未定义”
  • 有没有办法在java中获取上述文档的字段类型? stackoverflow.com/users/5084000/ravi-shankar
  • 你是指文档中所有字段的字段类型?
【解决方案2】:

我已经这样做并工作了:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 2018-10-18
        • 1970-01-01
        • 2013-05-06
        • 2021-11-17
        相关资源
        最近更新 更多