Keka Bron
Keka Bron

Reputation: 439

How to only get from MongoDB documents that match a specific filter using Java

My MongoDB Documents are like this:

"_id":"C\Users...\1.html"{
"data": Object[
        gambia:1
        estonia:1
        ...etc
        ]
}

I don't know if I wrote correctly the structure, so here you have a picture:

enter image description here

My problem is that I want to get from DB all Documents that match a specific word given. For example if the user enters "car" I need all the documents that in its data have the word car. But I couldn't find how to do it.

What I tried? I tried to get the first document that matches the word "gambia" which I know it exists in the first Document:

    MongoClient mongoClient = MongoClients.create();
    MongoDatabase database = mongoClient.getDatabase("motor");

    MongoCollection<Document> collection = database.getCollection("dictionary");
    String word = "gambia";
    Document myDoc = collection.find(Filters.eq("data", word)).first();
    System.out.println(myDoc);

But I'm getting a null pointer exception.

Upvotes: 0

Views: 1015

Answers (1)

Paplusc
Paplusc

Reputation: 1130

You can achieve this using the mongodb function $exists.

This function tells you if a determinated field, is in your collection.

For example:

MongoCollection<Document> collection = database.getCollection("dictionary");

String word = "gambia";

DBObject query = new BasicDBObject("data." + word, new BasicDBObject(
            "$exists", true));

Document myDoc = collection.find(query);
System.out.println(myDoc);

Upvotes: 1

Related Questions