Why eq doesn't exist for mongo-java-driver?

Viewed 8227

I've found in mongodb tutorial for java about how to query from mongo collection but the eq which they use doesn't work for me! Do you know how to filter documents from a collection with mongo and java?

This is my try:

package Database;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class StackOverflow {

    public static void main(String[] args) {

        // insert something to mongo:
        final String URI = "mongodb://localhost:27017";
        final String DB = "StackOverflowQuestion";
        final String COLLECTION = "eqDoesntExcist";

        MongoClientURI connection = new MongoClientURI(URI);
        MongoClient mongo = new MongoClient(connection);
        MongoDatabase database = mongo.getDatabase(DB);
        MongoCollection<Document> collection =  database.getCollection(COLLECTION);

        Document doc = new Document("name", "Troy").append("height", 185);
        collection.insertOne(doc);

        doc = new Document("name", "Ann").append("height", 175);
        collection.insertOne(doc);

        // read something from mongo
        FindIterable<Document> findIt = collection.find(eq("name", "Troy"));
        // ERROR!!! the method eq(String, String) is undefined!

        mongo.close();

    }

}

I want something like:

SELECT * from eqDoesntExcist WHERE name = "Troy"
2 Answers

You can use an eq Filter there as:

 Bson bsonFilter = Filters.eq("name", "Troy");
 FindIterable<Document> findIt = collection.find(bsonFilter);

or else to make it look the way doc suggests include a static import for the method call Filters.eq

import static com.mongodb.client.model.Filters.eq;

and further use the same piece of code as yours :

FindIterable<Document> findIt = collection.find(eq("name", "Troy")); // static import is the key to such syntax

you can not do this:

collection.find(eq("name", "Troy"));

because the compiler will expect in your class StackOverflow a method with the name eq and this is not what you need..

what you are looking for is defined in the Filter class

public static <TItem> Bson eq(String fieldName, Item value)

so it may be

collection.find(Filters.eq("name", "Troy"));
Related