foma foma - 1 year ago 52
Java Question

Retrive a set of documents from array in MongoDB using Java driver

I have a MongoDB document structure like this:

"name": "list"
"config": "default"
"items": [
"email": ""
"status": true
"number": 123
"email": ""
"status": false
"number": 432

Now, how can I retrive multiple subdocuments that much certain criteria. For instance, I want to obtain all documents where status = true. I know that it is possible to use $elemMatch, but it returns only the first matching instance and I need ALL documents that correspond to the specified condition. Please show how can it be done with Java.

Answer Source

You can do it in Java as follows.

        Mongo mongo = new Mongo("localhost:27017");
        DB db = mongo.getDB("myDB");
        DBCollection coll = db.getCollection("myCollection");

        DBObject statusQuery = new BasicDBObject("status", true);
        DBObject elemMatchQuery = new BasicDBObject("$elemMatch", statusQuery);

        DBObject fields = new BasicDBObject();
        fields.put("items", elemMatchQuery);
        fields.put("name", 1);
        fields.put("config", 1);

        DBCursor cur = coll.find(new BasicDBObject(), fields);

        while (cur.hasNext()) {
            DBObject obj =;
            // Get fields from object