共計 1138 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中使用 MongoDB 進行模糊查詢可以使用正則表達式來實現。以下是一個使用 Java 驅動程序實現模糊查詢的例子:
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import java.util.Arrays;
public class Main {public static void main(String[] args) {// 連接到 MongoDB 數據庫
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoCredential credential = MongoCredential.createCredential("username", "database", "password".toCharArray());
// 指定要連接的數據庫
MongoDatabase database = mongoClient.getDatabase("mydb");
// 獲取要查詢的集合
MongoCollection<Document> collection = database.getCollection("mycollection");
// 構造查詢條件
Document query = new Document("name", java.util.regex.Pattern.compile("keyword"));
// 執行查詢
MongoCursor<Document> cursor = collection.find(query).iterator();
// 輸出結果
while (cursor.hasNext()) {Document document = cursor.next();
System.out.println(document.toJson());
}
// 關閉連接
mongoClient.close();}
}
在上述代碼中,我們使用 java.util.regex.Pattern 類來構建正則表達式,將其作為查詢條件傳遞給 find 方法進行模糊查詢。其中,"name"是要查詢的字段名,"keyword"是要模糊匹配的關鍵字。
請根據實際情況替換 localhost、27017、username、database 和password為相應的 MongoDB 連接信息。
丸趣 TV 網 – 提供最優質的資源集合!
正文完