如何在MongoDB Java中根据指定键值获取对应字段(含代码示例)
Fixing Your Java Code to Fetch Age by Name from MongoDB
Let's walk through fixing your code to get the age value for a specific Name (like "msr") in MongoDB. First, let's spot the key issues in your original code:
- You're passing
dbo(a random document fromfindOne()) tocollection.find()instead of your query object — this won't filter by theNameyou want. - The unused
newDocumentvariable is unnecessary for reading data. - You tried casting
ageto aString, but your sample data hasageas a numeric type (24), so we need to use an integer type instead. - Using the
admindatabase (a system database) isn't ideal for storing user data; we'll use a custom database/collection instead.
Corrected Full Code
package mongojava; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; public class javaconn { public static void main(String[] args) { // Use try-with-resources to auto-close the MongoClient and prevent resource leaks try (MongoClient client = new MongoClient("localhost", 27017)) { // Replace "testdb" with your actual database name DB db = client.getDB("testdb"); // Replace "users" with your actual collection name DBCollection collection = db.getCollection("users"); // Build query to match documents where Name equals "msr" BasicDBObject query = new BasicDBObject(); query.put("Name", "msr"); // Option 1: Use cursor to handle multiple matching documents DBCursor cursor = collection.find(query); while (cursor.hasNext()) { DBObject doc = cursor.next(); String name = (String) doc.get("Name"); // Cast to Integer since age is a numeric value in your sample data Integer age = (Integer) doc.get("age"); System.out.printf("Found: Name=%s, Age=%d%n", name, age); } cursor.close(); // Option 2: Use findOne() if you only expect one matching document (more efficient) DBObject singleDoc = collection.findOne(query); if (singleDoc != null) { System.out.printf("Single result: Name=%s, Age=%d%n", singleDoc.get("Name"), singleDoc.get("age")); } else { System.out.println("No document found with Name: msr"); } } catch (Exception e) { // Handle any connection/query errors e.printStackTrace(); } } }
Key Explanations
- Resource Management: The
try-with-resourcesblock automatically closes theMongoClientwhen done, which is best practice to avoid unclosed connections. - Query Filter: We pass the
queryobject (which specifiesName: "msr") tofind()orfindOne()to get only matching documents. - Type Handling: Since your sample data has
ageas an integer, we cast it toIntegerinstead ofString. If your actualagevalues are stored as strings, adjust the cast toString. - Database/Collection Names: Replace
testdbanduserswith your actual database and collection names — avoid using theadmindatabase for user data, as it's reserved for system operations.
内容的提问来源于stack exchange,提问作者Sidda Reddy
相关产品推荐
相关产品推荐

