[英]Querying data in MongoDB-Java to remove _id and show only specified field
我正在Eclipse中完成一個Java項目,作為我大學任務的一部分。 該項目的一個要求是將數據寫入文本文件並在另一個類中讀回。 但是,我決定使用MongoDB
而不是文本文件。
數據的格式如下所示:
當我從Mongo讀回數據時,我使用以下代碼:
MongoClientURI connectionString = new MongoClientURI("<My connection string>");
MongoClient mongoClient = new MongoClient(connectionString);
MongoDatabase database = mongoClient.getDatabase("Timeline");
MongoCollection<Document> collection = database.getCollection("HistoricalFigure");
MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
system.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
這很好用,並從我的Mongo collection
打印以下內容:
(忽略數據 - 隨意丟掉它)
我知道過去有類似的問題要求從結果中刪除_id字段等等 - 請為此道歉 - 但不幸的是,我無法將這些示例應用於我自己的代碼,因為它們確實有很大不同。
我想要實現的是,只需將Historical Figure
的值打印到控制台,就可以打印出來:
如果有人可以提供幫助,我會非常感激 - 我認為答案將位於collection.find()
但我只是不確定如何。
非常感謝,喬治
Mongo Java驅動程序v3.x為此提供了一個有用的投影快捷方式: Projections.excludeId()
。
但這只是語法上的糖: new BsonDocument("_id", new BsonInt32(0))
因此,如果您使用的是Mongo Java驅動程序版本> = 3.x,則只需將此投影添加到find()
調用中:
collection.find().projection(Projections.excludeId()).iterator();
如果您使用的是Mongo Java驅動程序版本<3.x,則只需將此投影添加到find()
調用中:
collection.find().projection(new BsonDocument("_id", new BsonInt32(0))).iterator();
此投影指示Mongo 不在 find
調用返回的任何文檔中包含_id
屬性。
U可以傳遞id設置為-1且歷史數字為1的對象文字。
Collection.find({},{'_ id':0,'歷史人物':1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.