7

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"
Naman
  • 27,789
  • 26
  • 218
  • 353
W W
  • 769
  • 1
  • 11
  • 26

2 Answers2

13

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
Naman
  • 27,789
  • 26
  • 218
  • 353
  • So why their tutorial is mistaken? – W W Sep 23 '17 at 19:15
  • @WW tutorial is not mistaken, have updated the answer. To use such format, you need to include a static import of the method in use. In your case `Filters.eq`. – Naman Sep 23 '17 at 19:17
  • **The method find(DBObject) in the type DBCollection is not applicable for the arguments (Bson)** . I keep on getting this when i am trying to execute the last statement – Vishal Roy Feb 14 '19 at 06:32
-1

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"));
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97