Reputation: 1650
I changed my MongoDB subdocument to an array from an object.
Here is what it looked like originally.
"transactions": {
"TX1234": {
"guid": "TX1234",
"amount": 102,
"email_sent": false
},
"TX1235": {
"guid": "TX1235",
"amount": 102,
"email_sent": true
}
}
I used to use this programmatic find operation.
var email_sent_lookup = {};
email_sent_lookup['transactions.' + transaction_guid + '.email_sent'] = true;
if(Donate.findOne(email_sent_lookup)){
return true;
}
How can I convert this to find inside of my array (which now looks like below)?
transactions: [
{
"guid": "TX1234",
"amount": 102,
"email_sent": false
},
{
"guid": "TX1235",
"amount": 102,
"email_sent": true
}
]
Upvotes: 0
Views: 41
Reputation: 4486
You will want to use $elemMatch
e.g:
MyCollection.findOne({
transactions: {
$elemMatch : {
email_sent: { $eq: true },
}
}
});
or shorthand:
MyCollection.findOne({
transactions: {
$elemMatch : {
guid: 'TX1234', // find the GUID
email_sent: true // did you send it? DID YOU SEND IT?!?
}
}
});
Upvotes: 1