简体   繁体   中英

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

I want to make a simple user search feature in Eclipse using MongoDB. Once a user inputs what they want to find within the database, all of the data that matches it will be printed out. How can I do this?

Here is my code so far:

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);
}

If i understood right, you are looking for some kind of wildcard search to match your names even if they are not an exact match?

I attached some code, which uses regular expressions to achieve wildcard search similar to SQL like %term%

Here it is:

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();
}

With MongoDB Java Driver v3.2.2 you can do something like this:

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

This returns all documents containing "Leslie" in the name field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM