George
George

Reputation: 57

Querying data in MongoDB-Java to remove _id and show only specified field

I'm completing a Java project in Eclipse as part of my university assignment. One of the requirements of the project is to write data to a text file and read it back in, in another class. I've decided, however, to use MongoDB rather than text files.

The format of the data looks like this:

Data

When I read the data back in from Mongo I use the following code:

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

This works great and prints the following from my Mongo collection:

Result

(Ignore the data - Just chucked it in randomly)

I know similar questions have been asked in the past about removing _id fields from the results and so on - So apologies for that - But unfortunately, I haven't been able to apply these examples to my own code as they do vary quite a bit.

What I would like to achieve from this is to print to the console just the value of Historical Figure so that it prints this:

Desired outcome

If anybody could assist I would really appreciate it - I assume the answer will lie somewhere within the collection.find() but I'm just unsure how.

Many thanks, George

Upvotes: 4

Views: 3733

Answers (2)

KrishnaSingh
KrishnaSingh

Reputation: 746

U can pass an object literal with id set to -1 and historical figure to 1.

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

Upvotes: 0

glytching
glytching

Reputation: 47935

Mongo Java driver v3.x provides a helpful projection shortcut for this: Projections.excludeId().

But that's just syntactic sugar over this: new BsonDocument("_id", new BsonInt32(0))

So, if you are using a Mongo Java driver version >= 3.x then just add this projection to your find() call:

collection.find().projection(Projections.excludeId()).iterator();

If you are using a Mongo Java driver version < 3.x then just add this projection to your find() call:

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

This projection instructs Mongo to not include the _id attribute in any documents returned by the find call.

Upvotes: 2

Related Questions