Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 894
W W Avatar asked Sep 23 '17 19:09

W W


1 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
like image 144
Naman Avatar answered Oct 07 '22 06:10

Naman