I have the following embedded data And I am trying to get all the transactions which have a same week number for a particular saved account based on the accountId
. I tried the following query but it returns an empty array.
savingsAccount.find({accountId: "123456789012345678", transactions: {weekNumber: 32}})
Any Ideas? Thanks so much in advance.
"savingsAccount":
{
"_id": "598cb8686739d49a6f59dbb4",
"accountId": "123456789012345678",
"__v": 2,
"transactions": [
{
"_id": "598cb8a86739d49a6f59dbb5",
"amount": 1234,
"weekNumber": 32,
"date": "2017-08-10T19:48:56.347Z"
},
{
"_id": "598cbb70a4a8f89c18309d87",
"amount": 1234,
"weekNumber": 32,
"date": "2017-08-10T20:00:48.241Z"
}
]
}
This ...
savingsAccount.find({
accountId: "123456789012345678",
'transactions.weekNumber': 32
})
... will return all documents for which accountId
is "123456789012345678" and the weekNumber
attribute of at least one subdocument in the transactions
array is 32.
Your original query returned no matches because the second predicate ( transactions: {weekNumber: 32}
) was attempting to match elements of the transactions
array with the value: {weekNumber: 32}
and, since that only represents part of a transactions document, no match was found.
Edit 1 : if you want to go further than this to only return the subdocuments in the transactions
array which have weekNumber=32
then you have to project and filter (available in versions >= 3.2). Here's an example:
db.savingsAccount.aggregate([
{$match: { accountId: "123456789012345678" }},
{$project: {
accountId: 1,
__v: 1,
transactions: {$filter: {
input: '$transactions',
as: 't',
cond: {$eq: ['$$t.weekNumber', 32]}
}}
}}
])
This will return all documents for which accountId
is "123456789012345678" and the weekNumber
attribute of at least one subdocument in the transactions
array is 32 and for each matched document it will filter the transactions
array such that only those subdocuments having weekNumber=32
are returned.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.