'Query over a field which is deep inside MongoDB collection using array of possible options
I have a list
of commentDocument
collection in MongoDB
where each has the following structure:
{
"commentName": "test comment",
"outputs": {
"extraDetails": [{
"name": "My Own Comment",
"amountPaidDetails": [{
"paidService": "PhonePe", // <--------HERE
"usdAmount": 80,
},{
"paidService": "GooglePay", // <--------HERE
"usdAmount": 50,
},{
"paidService": "Cash", // <--------HERE
"usdAmount": 15,
}]
}]
},
"lastUpdateDate": {
"$date": "2020-06-24T04:00:00.000Z"
},
"lastUpdatedBy": "michealJackson",
}
I have to write a MongoDB query passing a list of paidService names as input. And if the document from the DB has any of the paidServices from the list I've sent in the allocatedAmound
list, the document should be present in the returned list of documents.
Eg: I pass list ['WalletCash', 'GooglePay', 'BankingCredits']
, the above document should be present because it has a document with a paidService 'GooglePay'
.
How to write the query?
Solution 1:[1]
db.collection.aggregate([
{
$match: {
"outputs.extraDetails.amountPaidDetails.paidService": {
$in: [
"WalletCash",
"GooglePay",
"BankingCredits"
]
}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Light Yagami |