문제

I have a MongoDB document structure like this:

{ 
  "name": "list"
  "config": "default"
  "items": [
    {
      "email": "user1@mail.com"
      "status": true
      "number": 123
    },
    ...
    {
      "email": "user100@mail.com"
      "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.

도움이 되었습니까?

해결책

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

다른 팁

If you want all subdocuments from the list items in separate documents, you can $unwind the list. I also added filter matching status is 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();
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top