Query fields in a MongoDB Collection.

2020-06-17 03:32发布

问题:

I am trying to query specific fields in a mongodb collection. Here is my code and output:

    Mongo m = new Mongo();
    DB db = m.getDB( "mydb" );
    DBCollection coll = db.getCollection("student") ;


    // adding data 
    BasicDBObject moz = new BasicDBObject();
    moz.put("Name", "Mozammil");
    coll.insert(moz);



    DBCursor cursor = coll.find();


    while (cursor.hasNext()) {
        System.out.println(cursor.next());

    }

This returns the following:

{ "_id" : { "$oid" : "4f5a4477c5e80f71ece56797"} , "Name" : "Mozammil"}

However, i want only the Name part. Googling around, this should do the job.

    DBCursor cursor = coll.find({}, {'Name':1});


    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

But it is not working. Help please?

回答1:

You can use get on the returned document by the cursor to get the field you are looking for. Like this:

System.out.println(cursor.next().get("key"));


回答2:

I know you already accepted an answer, but it isn't exactly what you were asking for.

Here is some working code:

// get Mongo set up...
Mongo m = new Mongo();
DB db = m.getDB( "test" );
DBCollection coll = db.getCollection("test");

// insert a test record
coll.insert(new BasicDBObject("Name","Wes").append("x", "to have a second field"));

// create an empty query
BasicDBObject query = new BasicDBObject(); 
// configure fields to be returned (true/1 or false/0 will work)
// YOU MUST EXPLICITLY CONFIGURE _id TO NOT SHOW
BasicDBObject fields = new BasicDBObject("Name",true).append("_id",false);

// do a query without specifying fields (and print results)
DBCursor curs = coll.find(query);
while(curs.hasNext()) {
   DBObject o = curs.next();
   System.out.println(o.toString());
}

// do a query specifying the fields (and print results)
curs = coll.find(query, fields);
while(curs.hasNext()) {
   DBObject o = curs.next();
   System.out.println(o.toString());
}

The first query outputs:

{ "_id" : { "$oid" : "4f5a6c1603647d34f921f967"} , "Name" : "Wes" , "x" : "to have a second field"}

And the second query outputs:

{ "Name" : "Wes"}


回答3:

Take a look at DBCollection.find

BasicDBObject query = new BasicDBObject(); // because you have no conditions
BasicDBObject fields = new BasicDBObject("Name",1);
coll.find(query, fields);


回答4:

collection.find().projection(Projections.include("Name"))

this worked such well!!!



回答5:

BasicDBObject query = new BasicDBObject();

BasicDBObject fields = new BasicDBObject();
fields.put("name", 1);

DBCursor cursor = collection.find(query, fields);
while (cursor.hasNext()) {
    System.out.println(cursor.next());
}


回答6:

To get all nested keys:

    public static ArrayList<String> getKeys(Document it1) throws JSONException {

        ArrayList<String> result = new ArrayList<String>();
        ArrayList<String> resultTemp;
        String temp;
        Document doc;
        JSONArray jsa;

        int len, i;
        System.out.println(it1);
        String js = it1.toJson();
        JSONObject js1 = new JSONObject(js);

        Iterator<String> keys = js1.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            if (key.equals("_id")) {
                result.add(key);
                continue;
            }
            System.out.println(key);

            temp = js1.get(key).toString();
            if (temp.contains(":")) {
                jsa = new JSONArray(temp);
                len = jsa.length();
                for (i = 0; i < len; i++) {
                    JSONObject object = jsa.getJSONObject(i);
                    doc = Document.parse(object.toString());
                    System.out.println(doc);
                    resultTemp = getKeys(doc);
                    for (String keyTemp : resultTemp) {
                        if (!result.contains(key + "." + keyTemp))
                            result.add(key + "." + keyTemp);
                    }
                }
            } else {
                result.add(key);
            }

        }
        return result;
    }


回答7:

 db.getCollection('users').aggregate([
   {"$project":{"arrayofkeyvalue":{"$objectToArray":"$$ROOT"}}},
   {"$unwind":"$arrayofkeyvalue"},
   {"$group":{"_id":null,"columns":{"$addToSet":"$arrayofkeyvalue.k"}}}
 ]) 

Use the above query it will give you all the fields of a document. In this you will get nested field also.



标签: java mongodb