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

W W :

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 :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476039&siteId=1