[英]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())
閱讀此 MongoDB文檔以了解更多信息。
我已經完成了這個工作:
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);
}
您可以使用聚合框架來實現所需的功能:
db.getCollection('samplecollection')。aggregate([[$$ project:{field1:1,field2:1 .....,'_ id':0}}]))
https://docs.mongodb.com/manual/reference/operator/aggregation/project/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.