MongoClient 如果使用 Java 匹配,则返回数组中的单个项目

MongoClient Bring back individual items in an array if they match using Java

我有一个文件...

doc =  
    { 
        "Loan_Num"       : "Loan002",
        "Info" : "Loan for processing details."
        "Loan_Items" :   [
                            {
                                "Invoice_Num"  : "32134324",
                                "Quantity"  : 1,
                                "Amount_Required" : "£4"
                            },

                            {
                                "Book_Barcode"  : "22222",
                                "Quantity"  : 1,
                                "Amount_Required" : "£2"
                                "Amount_Payed" : true
                            }
                        ]
    };

我正在尝试创建一个查询以返回任何具有 "Amount_Required" 键但没有 "Amount_Payed" 键的结果。

所以从上面的文档中我希望得到这个结果...

    { 
        "Loan_Num"       : "Loan002",
        "Info" : "Loan for processing details."
        "Loan_Items" :   [
                            {
                                "Invoice_Num"  : "32134324",
                                "Quantity"  : 1,
                                "Amount_Required" : "£4"
                            }
                        ]
    };

这是我的 Java 代码...

 BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.append("Loan_Num", "Loan002");
    searchQuery.append("Loan_Items.Fine_Amount", new BasicDBObject("$exists", true));
    searchQuery.append("Loan_Items.Fine_Payed", new BasicDBObject("$exists", false));

问题是它没有 return 任何东西,因为 "Amount_Played" 存在于数组的第二个元素中。我怎样才能达到这个结果? - 非常感谢

您可以尝试使用 $elemMatch

您的查询将如下所示:

db.collection.find({"Loan_Items" : {$elemMatch : { "Amount_Required" : { $exists : true}, "Amount_Payed" : { $exists : false}}}})

希望对您有所帮助!