2

I have a collection with documents that have the following fields:

  • description
  • state
  • field_num

I would like to return a cursor to all the documents that meet the following critiria:

  • have status "complete"
  • and field_num greater than 100
  • and that their description does not contain "abc" pattern?

Is this query correct?

DBObject query = new BasicDBObject("$gte",99)
    .append("status","complete")
    .append("description", new BasicDBObject("$not", ".*abc")))

DBCursor cursor = collection.find("collection name", query, projection)
4
  • 1
    Did you try it? Did it work? Commented Jan 22, 2018 at 7:03
  • "is that query correct"? -> execute the query, check the results. Commented Jan 22, 2018 at 7:09
  • By the way,$gte is "greater than or equals 99". That is for sure not "greater than 100" Commented Jan 22, 2018 at 7:10
  • I tried it, I am getting an error when doing cursor.hasNext(). though I might have a problem in the query. Commented Jan 22, 2018 at 7:11

1 Answer 1

2

This query:

have status "complete"

and field_num greater than 100

and that their description does not contain "abc" pattern?

... can be expressed as follows:

Bson query =
        // where field_num > 100
        new BasicDBObject("field_num", new BasicDBObject("$gte", 100))

        // where status is ' complete'
        .append("status", new BasicDBObject("$eq", "complete"))

        // where description does not contain 'abc' 
        // note: this uses inverse matching since the $not operator
        // is not allowed with the $regex operator
        .append("description", new BasicDBObject("$regex", "^((?!abc).)*$"));

In versions of the Java driver > 3.0 this can also be expressed more simply as:

Bson query= Filters.and(
        Filters.gt("field_num", 100),
        Filters.eq("status", "complete"),
        Filters.regex("description", "^((?!abc).)*$")
);

The query is executed as follows:

MongoClient mongoClient = ...;

MongoCollection<Document> collection = mongoClient.getDatabase("...")
    .getCollection("...");

collection.find(query)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.