[英]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
: 我还添加了过滤器匹配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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.