我的数据库中有这三个用户,具有以下键:
乔恩 111
乔恩 222
乔恩 333
我目前写的代码只能通过key在数据库中找到一个用户。 我怎样才能返回所有这些用户?
public void getMongoDB() {
DB db = mongo.getDB("people");
DBCollection table = db.getCollection("users");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("key", "Jon-111"); // what do I do here to return all the 'Jon' users?
DBCursor cursor = table.find(searchQuery);
int dbSize = cursor.size(); // size is 1
while (cursor.hasNext()) {
logger.debug(""+cursor.next()+"\n");
}
logger.debug("users table");
}
提前致谢
最佳答案
如果您希望搜索“Starts with Jon”,请尝试:
searchQuery.put("key", java.util.regex.Pattern.compile("^Jon"));
您将需要使用正则表达式来执行此类查询,如我的示例所示。
为了您的利益,还有一些示例:
“以乔恩结尾”:
searchQuery.put("key", java.util.regex.Pattern.compile("Jon$"));
“包含乔恩”:
searchQuery.put("key", java.util.regex.Pattern.compile(".*Jon.*"));
关于java - Java中的MongoDb查找用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37219347/