使用 Java 驱动程序在 MongoDB 中查询数据的用户搜索功能

User search feature to Query data in MongoDB using the Java driver

我想使用 MongoDB 在 Eclipse 中创建一个简单的用户搜索功能。一旦用户输入他们想在数据库中查找的内容,所有匹配的数据都将被打印出来。我该怎么做?

到目前为止,这是我的代码:

public static void searchFirstName()
{
    System.out.println("Enter first name you are searching for:");
    search = userInput.nextLine();

    FindIterable<Document> iterable = db.getCollection("names").find(all("anyname", search));
    System.out.println(iterable);
}

如果我没理解错的话,您是在寻找某种通配符搜索来匹配您的名字,即使它们不是完全匹配?

附上一些代码,使用正则表达式实现类似SQL like %term%

的通配符搜索

这里是:

public static void main(String[] args) {
    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase db = mongo.getDatabase("myDatabase");

    List<Document> someDummyData = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        someDummyData.add(new Document("name", "Leslie" + i));
    }
    someDummyData.add(new Document("name", "John Wayne"));
    someDummyData.add(new Document("name", "Wayne"));
    someDummyData.add(new Document("name", "Acme"));
    someDummyData.add(new Document("name", "Leslie"));

    db.getCollection("names").insertMany(someDummyData);

    //we will have 24 names in our database
    System.out.println(db.getCollection("names").count());

    //obtain the search term ....
    String searchTerm = "Leslie";

    //an index is a good idea, if we want to use wildcard search... 1 means ascending order
    db.getCollection("names").createIndex(new Document("name", 1));

    //we will find exactly one element      -> this is exact match like in SQL: where name = searchTerm
    Iterable<Document> search1 =  db.getCollection("names").find(new Document("name", searchTerm));

    for(Document search : search1) {
        System.out.println("Exact match: " + search);
     }


    //we will find a few matches -> this is wildcard match like in SQL: where name LIKE %searchTerm$

    Iterable<Document> search2 = db.getCollection("names").find(regex("name", String.format(".*((?i)%s).*",
            searchTerm)));

    for (Document search : search2) {
        System.out.println("Wildcard match: " + search);
    }

    mongo.close();
}

使用 MongoDB Java Driver v3.2.2 你可以这样做:

FindIterable<Document> iterable = collection.find(Document.parse("{name: {$regex: \"Leslie\"}}"));

这 returns 所有在 name 字段中包含 "Leslie" 的文档。