使用Java驱动程序从MongoDB中的数组中检索一组文档

时间:2013-09-11 09:04:16

标签: java mongodb mongodb-java

我有一个像这样的MongoDB文档结构:

{ 
  "name": "list"
  "config": "default"
  "items": [
    {
      "email": "user1@mail.com"
      "status": true
      "number": 123
    },
    ...
    {
      "email": "user100@mail.com"
      "status": false
      "number": 432
    },
   ]
}

现在,我如何能够检索多个特定标准的子文档。例如,我想获取 status = true 的所有文档。我知道可以使用 $ elemMatch ,但它只返回第一个匹配的实例,我需要与指定条件对应的 ALL 文档。请说明如何使用Java。

2 个答案:

答案 0 :(得分:2)

您可以使用Java完成以下操作。

        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 = cur.next();
            // Get fields from object
        }

答案 1 :(得分:0)

如果您希望列表items中的所有子文档位于不同的文档中,则可以$unwind列表。我还添加了过滤器匹配statustrue

try (MongoClient client = new MongoClient()) {

        MongoDatabase db = client.getDatabase("myDB");
        MongoCollection<BsonDocument> collection = db.getCollection("myColl", BsonDocument.class);

        MongoCursor<BsonDocument> cursor =
                collection.aggregate(Arrays.asList(new Document("$unwind", "$items"),
                                                    new Document("$match", new Document("items.status", true)))).iterator();

        try {
            while (cursor.hasNext()) {
                // I think this is what you need
                BsonDocument bsonDocument = cursor.next().getDocument("items");

                // and if you just want emails
                String email = bsonDocument.get("email").asString().getValue();
                System.out.println(email);
            }

        } finally {
            cursor.close();
        }
    }