在 MongoDB Java 驱动程序中创建查询

Creating query in MongoDB Java driver

我有一个包含具有以下字段的文档的集合:

我想 return 游标到满足以下条件的所有文档:

这个查询是否正确?

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

DBCursor cursor = collection.find("collection name", query, projection)

这个查询:

have status "complete"

and field_num greater than 100

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

...可以表示为:

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).)*$"));

在 Java 驱动程序 > 3.0 的版本中,这也可以更简单地表示为:

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

查询执行如下:

MongoClient mongoClient = ...;

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

collection.find(query)