在MongoDB中搜索嵌入式阵列(使用Java)
我有一份文件在MongoDB中搜索嵌入式阵列(使用Java),java,mongodb,Java,Mongodb,我有一份文件investor,内容如下: { "_id": ObjectId("588ced539df613f71a697bb9"), "idInvestor": 1, "username": "Alexander Hamilton", "password": "123456", "email": "alex.hamil@gmail.com", "name": "Alexander Hamilton", "idProfile": 1,
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());
Investor=新投资者();
MongoClient MongoClient=新的MongoClient(“本地主机”,27017);
MongoDatabase=mongoClient.getDatabase(“finnovate”);
MongoCollection collection=database.getCollection(“投资者”);
Document myDoc=collection.find(eq(“username”,username)).first();
investor.setIdInvestor(myDoc.getDouble(“idInvestor”).intValue());
但我不明白如何才能得到所有的IDQ值。有人能解释一下吗?在Mongo中,文档数组是“questionAnswer”,所以在Java中,它将是文档的数组列表。从myDoc,您可以执行以下操作:
List<Document> questionAnswers = (List<Document>)myDoc.get("questionAnswer");
for (Document questionAnswer: questionAnswers) {
// do whatever you need here
System.out.println(questionAnswer.getString("idQuestion"));
}
和结果处理块:
Block<Document> doWhateverYouNeed = new Block<Document>() {
@Override
public void apply(final Document document) {
//do whatever you need here
System.out.println(document.toJson());
}
};
Block dowhateveryouneeded=new Block(){
@凌驾
公开作废申请(最终文件){
//你需要什么就做什么
System.out.println(document.toJson());
}
};
Block<Document> doWhateverYouNeed = new Block<Document>() {
@Override
public void apply(final Document document) {
//do whatever you need here
System.out.println(document.toJson());
}
};