简体   繁体   English

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

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

I have a MongoDB document structure like this: 我有一个像这样的MongoDB文档结构:

{ 
  "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 . 例如,我想获取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. 我知道可以使用$ elemMatch ,但是它仅返回第一个匹配的实例,并且我需要与指定条件相对应的所有文档。 Please show how can it be done with Java. 请展示如何使用Java完成。

You can do it in Java as follows. 您可以按照以下步骤在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
        }

If you want all subdocuments from the list items in separate documents, you can $unwind the list. 如果希望将列表items中的所有子文档放在单独的文档中,则可以$unwind该列表。 I also added filter matching status is true : 我还添加了过滤器匹配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();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Java驱动程序从存储在MongoDB中的数组中检索Integer和Timestamp值 - How to retrive Integer and Timestamp value from array stored in MongoDB with Java Driver 使用 mongodb java 驱动程序保证 mongodb 文档中的字段顺序 - guarantee fields order in a mongodb documents using mongodb java driver 如何使用Java驱动程序在MongoDB中更新数组的嵌入式文档中的字段值 - How to Update fields value in embedded documents of an Array in MongoDB using Java Driver 使用 MongoDB-Java 驱动程序从数组中删除条目 - Remove an entry from array using MongoDB-Java driver 使用async-driver for Java时,并非所有文档都插入到MongoDB中 - Not all documents are inserted in MongoDB when using the async-driver for Java 如何使用 Java mongodb 驱动程序中的“_id”字段查询文档? - How to query documents using "_id" field in Java mongodb driver? 如何使用mongodb Java驱动程序更新较旧的文档? - How can I update older documents using mongodb Java driver? 如何避免使用 mongodb Java 驱动程序复制文档 - How to avoid copying documents using mongodb Java driver 无法使用mongodb java驱动程序将文档插入集合 - not able to insert documents into collection using mongodb java driver 如何使用 MongoDB 的 Java 驱动程序将多个文档合并为一个? - How merge many documents into one using MongoDB's Java Driver?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM