MongoDB Java - 将查询转换为mongodb Java驱动程序

时间:2016-04-07 20:40:17

标签: java mongodb

我有一个奇怪的问题。我有一个查询,我确信它有效,但是当我用Java翻译它时,它不会返回任何内容。

MongoDB查询是:

db.births.aggregate([
    {
        "$match": {
            "day" : "March_13",
            "events.year": "1929",
            "events.info": /American/
        }
    },
    { "$unwind": "$events" },
    {
        "$match": {
            "day" : "March_13",
            "events.year": "1929",
            "events.info": /American/
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "day": { "$first": "$day" },
            "events": { "$push": "$events" }
        }
    }

])

Java代码是:

AggregateIterable<Document> result = mongoDatabase.getCollection(category).
    aggregate(
            Arrays.asList(
                    new Document("$match",
                            new Document("day", day).
                                    append("events.year", year).
                                    append("events.info", "/" + word + "/")),
                    new Document("$unwind", "$events"),
                    new Document("$match",
                            new Document("day", day).
                                    append("events.year", year).
                                    append("events.info", "/" + word + "/")),
                    new Document("$group",
                            new Document("_id", "$_id").
                                    append("day", new Document("$first", "$day")).
                                    append("events", new Document("$push", "$events")))));

请查看并告诉我,我将其翻译成Java的方式是错误的还是其他的。

谢谢!

1 个答案:

答案 0 :(得分:0)

在Java中你可以试试这个:

String m = "American";
DBObject eventInfoObject = new BasicDBObject(
  "events.info", 
  java.util.regex.Pattern.compile(m)
);

这会向MongoDB服务器发送查询{ "events.info" : { "$regex" : "American"}}

在您的代码中替换:

"/" + word + "/"

with:

java.util.regex.Pattern.compile(word)