如何使用Java MongoDB驱动程序使用正则表达式和复杂条件编写集合查找代码?

如何使用Java MongoDB驱动程序使用正则表达式和复杂条件编写集合查找代码?,java,regex,mongodb,Java,Regex,Mongodb,我在MongoDB中有以下查询: db.cache.find({objectKey: { $regex: 'Bos*'}, cacheVersionString:'08/03/15_11:05:09'}, { _id:0, objectData:0, lastModified :0, productCode:0}) 另外,我还想计算记录的数量,这在MongoShell中可以通过使用count来实现 db.cache.find({objectKey: { $regex: 'Bos*'}, cac

我在MongoDB中有以下查询:

db.cache.find({objectKey: { $regex: 'Bos*'}, cacheVersionString:'08/03/15_11:05:09'},
{ _id:0, objectData:0, lastModified :0, productCode:0})
另外,我还想计算记录的数量,这在MongoShell中可以通过使用count来实现

db.cache.find({objectKey: { $regex: 'Bos*'}, cacheVersionString:'08/03/15_11:05:09'},
{ _id:0, objectData:0, lastModified :0, productCode:0}).count()

如何使用Java MongoDB驱动程序(版本3)在Java中编写类似查询?

构造查询实际上只是创建BSON文档表示,它基本上与标准HashMap或列表接口相同(视情况而定):

    Document query = new Document("objectKey",new Document( "$regex","Bos"))
        .append("cacheVersionString","08/03/15_11:05:09");

    Document projection = new Document("_id",0)
        .append("objectData",0)
        .append("lastModified",0)
        .append("productCode",0);

    MongoCursor<Document> cursor = collection.find(query).projection(projection).iterator();
documentquery=新文档(“objectKey”,新文档(“$regex”,“Bos”))
附加(“cacheVersionString”,“08/03/15_11:05:09”);
文档投影=新文档(“\u id”,0)
.append(“objectData”,0)
.append(“lastModified”,0)
.append(“产品代码”,0);
MongoCursor=collection.find(query).projection(projection.iterator();
这与在MongoDB shell中构造查询的方式基本相同

或者,如果您觉得更符合逻辑,可以使用生成器界面:

    QueryBuilder builder = QueryBuilder.start();

    builder.and("objectKey").regex(Pattern.compile("box"));
    builder.and("cache_version_string").is("08/03/15_11:05:09");

    BasicDBObject query = (BasicDBObject)builder.get();

    Bson projection = Projections.exclude(
            "_id",
            "obectdata",
            "lasModified",
            "productCode"
    );

    MongoCursor<Document> cursor = collection.find(query).projection(projection).iterator();

    while (cursor.hasNext()) {
        Document doc = cursor.next();
        System.out.println(doc.toJson());
    }
QueryBuilder builder=QueryBuilder.start();
builder.and(“objectKey”).regex(Pattern.compile(“box”);
生成器和(“缓存版本字符串”)是(“08/03/15\u 11:05:09”);
BasicDBObject查询=(BasicDBObject)builder.get();
Bson projection=Projections.exclude(
“_id”,
“obectdata”,
“改质”,
“产品代码”
);
MongoCursor=collection.find(query).projection(projection.iterator();
while(cursor.hasNext()){
Document doc=cursor.next();
System.out.println(doc.toJson());
}

这两种形式基本上都为“查询”和“投影”组件构造BSON,并将它们作为参数发送给
.find()
方法。如果适合您的话,还有类类型定义。

您检查过了吗?我找不到如何在Java find中使用正则表达式,在这个文档eitherOkay中,我还没有深入研究这个文档。但是通过使用C#驱动程序,还有一些需要改进的地方。谢谢。我还加了一个关于伯爵的问题,你知道吗?