I have a document...
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
}
]
};
I'm trying to create a query to bring back any results that have the "Amount_Required" key but don't have the "Amount_Payed" key.
So from the above document I would expect this result...
{
"Loan_Num" : "Loan002",
"Info" : "Loan for processing details."
"Loan_Items" : [
{
"Invoice_Num" : "32134324",
"Quantity" : 1,
"Amount_Required" : "£4"
}
]
};
This is my Java code...
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));
Problem being is it doesn't return anything since the "Amount_Played" exists in the second element in the array. How could I achieve this result ? - Many Thanks
You could try using $elemMatch:
Your query would look something like this:
db.collection.find({"Loan_Items" : {$elemMatch : { "Amount_Required" : { $exists : true}, "Amount_Payed" : { $exists : false}}}})
Hope this helps!