Search code examples
javamongodbmongodb-querymongodb-java

Creating query in MongoDB Java driver


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)

Solution

  • 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)