Java MongoDB通过邮件regex查找文档

时间:2015-01-08 23:15:06

标签: java regex mongodb-query

我正在编写一些应用程序,我想找到所有使用雅虎邮件的员工。我的代码在下面,并没有正常工作。最简单的方法是什么?

public static void findAllEmplyestUsingYahooMail(){
        try {

            MongoClient mongoClient = new MongoClient();
            DB database = mongoClient.getDB("employeeDB");
            DBCollection collection = database.getCollection("employeesCollection");

            BasicDBObject regexQuery = new BasicDBObject();
            regexQuery.put("mail", new BasicDBObject("$regex", "^@yahoo.com")
                .append("$options", "is"));

            DBCursor cursor = collection.find(regexQuery);
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }


        } catch (UnknownHostException e) {

            e.printStackTrace();
        }
    }

2 个答案:

答案 0 :(得分:0)

在没有实际执行的情况下查看它,我认为问题出在正则表达式中。它应该是这样的:

regexQuery.put("mail", new BasicDBObject("$regex", ".+@yahoo.com") ...

@Codemaster您是否在mongo shell中尝试了相同的查询?它在mongo shell中工作。

答案 1 :(得分:0)

请尝试这样做:

regexQuery.put("mail", java.util.regex.Pattern.compile("^@yahoo.com"))

它会转换为正则表达式查询:

db.yourcollection.find({"name": /^@yahoo.com/})