簡體   English   中英

在MongoDB中搜索嵌入式數組(使用Java)

[英]Searching for an embedded array in MongoDB (with Java)

我有一個文件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的所有idinvestor: 1以將它們存儲在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值。 請問有人可以對此進行說明嗎?

在Mongo中,您有一系列文檔作為“ questionAnswer”,因此在Java中,它將是Document的ArrayList。 在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());
     }
};  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM