1

我有一个这样的 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,但它只返回第一个匹配的实例,我需要与指定条件相对应的所有文档。请说明如何使用 Java 来完成。

4

2 回答 2

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
        }
于 2013-09-11T10:20:37.933 回答
0

如果您想将列表中的所有子文档items放在单独的文档中,您可以$unwind列出列表。status我还添加了过滤器 匹配true

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();
        }
    }
于 2016-10-31T09:10:39.957 回答