so i try to query data from mongodb using this line of code :
forms = await AllForm.find({
answers: {
$all: [{ $elemMatch: { dateCreate: "2022-10-25" } }],
},
it supposed to return date that are only "2022-10-25", but it turns out that it selected all the dates with result as below:
"status": true,
"message": "LIST_FORM",
"forms": [
{
"_id": "635711356b220b918529c29a",
"formId": "635711356b220b918529c298",
"title": "Quality",
"department": "Quality",
"answers": [
{
"username": "[email protected]",
"dateCreate": "2022-10-25",
"Keterangan": "[email protected]",
"Jam_Kerja": "14:09"
},
{
"username": "[email protected]",
"dateCreate": "2022-10-24",
"Keterangan": "[email protected]",
"Jam_Kerja": "10:50"
}
],
"createdAt": "2022-10-24T22:27:01.673Z",
"updatedAt": "2022-10-24T22:32:27.683Z",
"__v": 0
},
{
"_id": "63571d2285d6fb180cfa9f84",
"formId": "63571d2285d6fb180cfa9f82",
"title": "Quality_2",
"department": null,
"answers": [
{
"username": "[email protected]",
"dateCreate": "2022-10-25",
"Test": "[email protected]",
"Date": "2022-10-12T00:00:00.000Z"
},
{
"username": "[email protected]",
"dateCreate": "2022-10-25",
"Test": "[email protected]",
"Date": "2022-10-12T00:00:00.000Z"
}
],
"createdAt": "2022-10-24T23:17:54.995Z",
"updatedAt": "2022-10-24T23:19:29.981Z",
"__v": 0
}
]
can someone please tell me where did i do wrong for the query?
CodePudding user response:
Think that the .find()
query unable to complete such a complex projection.
You may look for aggregation query.
$match
- With dot notation, find the document(s withforms
array contain the document withdateCreate
is "2022-10-25" in nestedanswers
array.$set
- Set theanswers
array.2.1.
$filter
- Filter the matched document in theanswers
array.
forms = await AllForm.aggregate([
{
$match: {
"answers.dateCreate": "2022-10-25"
}
},
{
$set: {
answers: {
$filter: {
input: "$answers",
cond: {
$eq: [
"$$this.dateCreate",
"2022-10-25"
]
}
}
}
}
}
])