问题
{
"_id": {
"$oid": "5f244a0c9b20935b3bdc2cd9"
},
"user": {
"rid": "5f12ba968ca0084ee7f7ea9b",
"name": "",
"phone": “0123456789”
},
"clazz": “Test”,
"enrolment_history": [{
"_id": {
"$oid": "5f245e2f1906715c9e52d675"
},
"start_from": {
"$date": "2020-06-30T18:30:00.000Z"
},
"expires_in": {
"$date": "2020-07-31T18:30:00.000Z"
},
"enrollment_date": {
"$date": "2020-06-30T18:30:00.000Z"
},
"payment_method": "Free",
"status": "SUCCESS",
"clazz_transaction": "5f3e74f8d26e962003103c11",
"month": "2020-6"
}, {
"_id": {
"$oid": "5f3e790c1e3c741f9eb6e53b"
},
"start_from": {
"$date": "2020-07-31T18:30:00.000Z"
},
"expires_in": {
"$date": "2020-08-31T18:30:00.000Z"
},
"enrollment_date": {
"$date": "2020-07-31T18:30:00.000Z"
},
"payment_method": "Free",
"status": "SUCCESS",
"clazz_transaction": "5f3e790c1e3c741f9eb6e53a",
"month": "2020-7"
}, {
"_id": {
"$oid": "5f5763bfc2464554c15a2b28"
},
"start_from": {
"$date": "2020-08-31T18:30:00.000Z"
},
"expires_in": {
"$date": "2020-09-30T18:30:00.000Z"
},
"enrollment_date": {
"$date": "2020-09-08T10:58:07.333Z"
},
"payment_method": "Free",
"status": "SUCCESS",
"clazz_transaction": "5f5763bfc2464554c15a2b27",
"month": "2020-8"
}
}
I have that kind of document list, so i need to fetch this document using below filters
{"phone":"0123456789","enrolment_history.month":"2020-6"}
Output => (remove other data inside of enrolment_history array)
{
"_id": {
"$oid": "5f244a0c9b20935b3bdc2cd9"
},
"user": {
"rid": "5f12ba968ca0084ee7f7ea9b",
"name": "",
"phone": “0123456789”
},
"clazz": “Test”,
"enrolment_history": [{
"_id": {
"$oid": "5f245e2f1906715c9e52d675"
},
"start_from": {
"$date": "2020-06-30T18:30:00.000Z"
},
"expires_in": {
"$date": "2020-07-31T18:30:00.000Z"
},
"enrollment_date": {
"$date": "2020-06-30T18:30:00.000Z"
},
"payment_method": "Free",
"status": "SUCCESS",
"clazz_transaction": "5f3e74f8d26e962003103c11",
"month": "2020-6"
}
}
回答1:
You can use aggregate()
method,
$match
filter documents as per your conditions$set
to get filtered using$filter
ModelName.aggregate([
{
$match: {
"user.phone": "0123456789",
"enrolment_history.month": "2020-6"
}
},
{
$set: {
"enrolment_history": {
$filter: {
input: "$enrolment_history",
cond: { $eq: ["$$this.month", "2020-6"] }
}
}
}
}
])
Playground
来源:https://stackoverflow.com/questions/64940988/mongodb-query-fetch-with-without-unwanted-data-using-nestjs