在MongoDB中搜索嵌入式数组(使用Java)

时间:2017-01-28 20:13:42

标签: java mongodb

我有一份文件investor,内容如下:

{
    "_id": ObjectId("588ced539df613f71a697bb9"),
    "idInvestor": 1,
    "username": "Alexander Hamilton",
    "password": "123456",
    "email": "alex.hamil@gmail.com",
    "name": "Alexander Hamilton",
    "idProfile": 1,
    "questionAnswer": [{
        "**idQuestion**": 1,
        "idAnswer": 1
    }, {
        "**idQuestion**": 2,
        "idAnswer": 1
    }...]
}

我正在尝试编写一个返回idinvestor: 1的所有idQuestions的查询,以将它们存储在ArrayList中。我能够得到其他不属于嵌入式的属性:

Investor investor= new Investor();
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase("finnovate");
MongoCollection<Document> collection = database.getCollection("investor");
Document myDoc = collection.find(eq("username", username)).first();
investor.setIdInvestor(myDoc.getDouble("idInvestor").intValue());

但我不明白如何获得所有idQuestion值。有人可以对此有所了解吗?

1 个答案:

答案 0 :(得分:0)

你有一系列文件作为&#34; questionAnswer&#34;在Mongo中,所以在Java中它将是DocumentList的Document。从myDoc你可以这样做:

List<Document> questionAnswers = (List<Document>)myDoc.get("questionAnswer");
for (Document questionAnswer: questionAnswers) {
    // do whatever you need here
    System.out.println(questionAnswer.getString("idQuestion"));
}

或者您可以使用聚合直接选择idQuestion。

collection.aggregate(Arrays.asList(
        Aggregates.match(Filters.eq("username", username)),
        Aggregates.unwind("$questionAnswer"),
        Aggregates.project(Projections.fields(Projections.excludeId(), 
                Projections.computed("idQuestion", "$questionAnswer.idQuestion"), 
                Projections.computed("idAnswer", "$questionAnswer.idAnswer")
        ))
)).forEach(doWhateverYouNeed);

处理结果块:

Block<Document> doWhateverYouNeed = new Block<Document>() {
     @Override
     public void apply(final Document document) {
         //do whatever you need here
         System.out.println(document.toJson());
     }
};