Scala MongoDB查询无数据返回,命令行可正常获取数据求助
Hey Salim, let's dive into why your Scala code isn't returning data even though the MongoDB shell works perfectly. Here are the key areas to check, along with actionable fixes:
1. Fix Driver Version Compatibility
Your shell is v3.6.3 but the server is v3.4.4—version mismatches can cause subtle compatibility issues, especially with authentication or query handling. Make sure your Scala MongoDB driver version aligns with the server version:
- For MongoDB 3.4, use the Mongo Scala Driver 2.2.x series (this branch is explicitly compatible with 3.4 servers).
Add this to your SBT dependencies:
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "2.2.11"
2. Verify Connection String & Authentication
Double-check that your Scala code uses the exact same connection parameters as your shell command. Common mistakes here include missing credentials, wrong database names, or incorrect authentication sources.
Here's a correct connection setup matching your shell command:
import org.mongodb.scala._ // Match the shell's connection details exactly val mongoClient: MongoClient = MongoClient( "mongodb://salimfadhley:secretpassowrd@database.foocorp.com:27017/mydatabase" ) val database: MongoDatabase = mongoClient.getDatabase("mydatabase") val collection: MongoCollection[Document] = database.getCollection("mycollection")
If your user is authenticated against the admin database (not mydatabase), add ?authSource=admin to the connection string:
"mongodb://salimfadhley:secretpassowrd@database.foocorp.com:27017/mydatabase?authSource=admin"
3. Handle Asynchronous Query Results
The Scala MongoDB driver is asynchronous by default—unlike the shell, calling find() won't immediately return data. You need to properly resolve the Future to get results:
import scala.concurrent.Await import scala.concurrent.duration._ import scala.util.{Failure, Success} // Execute the query and wait for results (for testing/debugging) val queryFuture = collection.find().toFuture() Await.result(queryFuture, 10.seconds) match { case Success(documents) => println(s"Found ${documents.size} documents!") case Failure(error) => println(s"Query failed: ${error.getMessage}") }
For production apps, use onComplete instead of Await to handle results non-blockingly.
4. Check Collection Name Case Sensitivity
MongoDB is case-insensitive on Windows but case-sensitive on Unix-like systems. If your Scala code uses a different case than the actual collection name (e.g., MyCollection instead of mycollection), it will return empty results. Ensure the collection name in code exactly matches what you see in the shell.
5. Explicitly Set Authentication Mechanism
MongoDB 3.4 uses SCRAM-SHA-1 as the default authentication mechanism. If your driver is using a newer mechanism (like SCRAM-SHA-256), it might fail silently. Force the correct mechanism in your connection string:
"mongodb://salimfadhley:secretpassowrd@database.foocorp.com:27017/mydatabase?authMechanism=SCRAM-SHA-1"
6. Log & Inspect Exceptions
Always capture and log exceptions—many issues (like authentication failures, connection timeouts, or invalid queries) are hidden without proper error handling. The Failure block in the code above will reveal exactly what's going wrong.
Start with these steps, and if you hit any specific errors, I can help narrow it down further!
内容的提问来源于stack exchange,提问作者Salim Fadhley

