monkey intern
monkey intern

Reputation: 726

How to query for several, specific fields

So I am exploring how to query mongo from java, and I found several different ways of querying this, and I'm not sure if I'm missing some nuance, thus not fully understanding the queries, or they are the same.

So far I found, for java driver v3.2, this:

collection.find().projection(fields(include("x", "y"), excludeId()))

And I've been told this should work:

BasicDBobject query = new BasicDBObject("x", x).append("y", y);//This example may not compile, I haven't tried it, I'm more talking about the idea and concept.

This query would go with a find(), findOne(), distinct(), and so on.

        String fields = "averageSpeed";
        coll = db.getCollection(strMongoCollection);
        coll.find(fields, query));

So, are both right approaches? Or its purpose is deferent

Upvotes: 0

Views: 148

Answers (1)

mtj
mtj

Reputation: 3554

You always have the option of using the old unwieldy Bson objects yourself, but for the 3.2 driver I'd rather go with the Filters and Projections helper classes.

Thus, a simple search with some criteria can be sent as

collection.find(Filters.eq("myfield", "myvalue"))

For selecting certain fields only, you append a projection:

collection.find(Filters.eq("myfield", "myvalue"))
    .projection(Projections.include("myfield", "anotherfield"))

Apart from the more elegant code of the new API, the queries do the same as the BasicDBObject-based calls.

Upvotes: 1

Related Questions