You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 from findOne()) to collection.find() instead of your query object — this won't filter by the Name you want.
  • The unused newDocument variable is unnecessary for reading data.
  • You tried casting age to a String, but your sample data has age as a numeric type (24), so we need to use an integer type instead.
  • Using the admin database (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

  1. Resource Management: The try-with-resources block automatically closes the MongoClient when done, which is best practice to avoid unclosed connections.
  2. Query Filter: We pass the query object (which specifies Name: "msr") to find() or findOne() to get only matching documents.
  3. Type Handling: Since your sample data has age as an integer, we cast it to Integer instead of String. If your actual age values are stored as strings, adjust the cast to String.
  4. Database/Collection Names: Replace testdb and users with your actual database and collection names — avoid using the admin database for user data, as it's reserved for system operations.

内容的提问来源于stack exchange,提问作者Sidda Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:58:24