在MongoDB Java中查询数据以删除_id并仅显示指定字段

在MongoDB Java中查询数据以删除_id并仅显示指定字段,java,mongodb,mongo-java,Java,Mongodb,Mongo Java,作为我大学作业的一部分,我正在Eclipse中完成一个Java项目。该项目的一个要求是将数据写入文本文件,然后在另一个类中将其读回。但是,我决定使用MongoDB而不是文本文件 数据的格式如下所示: 当我从Mongo读回数据时,我使用以下代码: MongoClientURI connectionString = new MongoClientURI("<My connection string>"); MongoClient mongoClient = new MongoClien

作为我大学作业的一部分,我正在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();
    }
MongoClientURI connectionString=newmongoclienturi(“”);
MongoClient MongoClient=新的MongoClient(connectionString);
MongoDatabase数据库=mongoClient.getDatabase(“时间线”);
MongoCollection collection=database.getCollection(“HistoricalFigure”);
MongoCursor=collection.find().iterator();
试一试{
while(cursor.hasNext()){
system.out.println(cursor.next().toJson());
}
}最后{
cursor.close();
}
这非常有效,可以从我的
Mongo收藏中打印以下内容:

(忽略数据-只是随机插入)

我知道过去也有人问过类似的问题,比如从结果中删除_id字段等等——为此我深表歉意——但不幸的是,我无法将这些示例应用到我自己的代码中,因为它们的差异很大

我想从中获得的是,仅将
历史图形的值打印到控制台,以便它打印以下内容:

如果有人能提供帮助,我将非常感激——我想答案可能就在
集合中的某个地方。find()
,但我不确定如何解决

非常感谢,,
George

Mongo Java驱动程序v3.x为此提供了一个有用的投影快捷方式:
Projections.excludeId()

但这只是语法上的甜点:
newbsondocument(“\u id”,newbsonint32(0))

因此,如果您使用的是Mongo Java驱动程序版本>=3.x,那么只需将此投影添加到您的
find()
调用:

collection.find().projection(Projections.excludeId()).iterator();
collection.find().projection(new BsonDocument("_id", new BsonInt32(0))).iterator();
如果您使用的是Mongo Java驱动程序版本<3.x,则只需将此投影添加到
find()
调用中:

collection.find().projection(Projections.excludeId()).iterator();
collection.find().projection(new BsonDocument("_id", new BsonInt32(0))).iterator();

此投影指示Mongo在
find
调用返回的任何文档中not包含
\U id
属性。

U可以传递id设置为-1、历史图形设置为1的对象文字


Collection.find({},{''u id':0,'Historical figure':1})

这是一个'raw'shell命令,我想OP是在问如何使用Mongo Java驱动程序来表达它。这个答案几乎完美,谢谢!我使用的是3.6,所以投影法是有效的。但是,这将打印到我的控制台
{“历史人物”:“John Cleese(1749年5月23日-1823年3月1日)-Maddog”}
-我是否可以简单地打印
John Cleese(1749年5月23日-1823年3月1日)-Maddog
?MongoDB正在向您返回一个
文档,此文档由一组键/值对组成(即,Historical Figure=John Cleese…)。此:
{“Historical Figure”:“John Cleese(1749年5月23日-1823年3月1日)-Maddog”}
只是该文档的一种表示形式。如果您想获取不带键的值,请使用:
document.getString(“Historical Figure”)
但您不能指示MongoDB返回没有键的值