Sorry if the title is confusing as I’m still learning to code. Here’s my code but it displays all objects in the array. I only want a specific object from the child schema to show while all the key-value in the parent to display.
var password = req.body.queryResult.parameters.password;
var appointmentNumber = req.body.queryResult.parameters.appointmentNumber;
db.db().collection('users').findOne({ "password": password, "appointment": { "$elemMatch":
{ "appointmentNumber": { "$eq": appointmentNumber } } } }, (err, result) => {
if (err || result == null) {
return res.json({
"fulfillmentText": "Sorry, cannot find an appointment with the password you provided."
});
} else {
console.log(result);
var firstName = result.firstName;
var lastName = result.lastName;
var appointmentDate = result.appointment[0].appointmentDate;
var status = result.appointment[0].appointmentStatus;
return res.json({
"fulfillmentText": "Good day " +
firstName + " " +
lastName + "! Your appointment that is scheduled on " +
appointmentDate + " is " +
status + "."
});
}
})
This is the output of the code above:
{
_id: new ObjectId("62189decc456ba291a4c330b"),
firstName: 'Joe',
lastName: 'Doe',
password: 'UOnlyMIbeu',
mobile: '09123456789',
email: 'test@gmail.com',
informationType: 'appointment',
appointment: [
{
appointmentNumber: 1035521,
appointmentDate: 2022-03-20T04:00:00.000Z,
appointmentStatus: 'Pending'
},
{
appointmentNumber: 295693,
appointmentDate: 2022-04-16T04:00:00.000Z,
appointmentStatus: 'Pending'
},
{
appointmentNumber: 780752,
appointmentDate: 2022-05-24T04:00:00.000Z,
appointmentStatus: 'Pending'
}
]
}
And here’s what I want to happen:
{
_id: new ObjectId("62189decc456ba291a4c330b"),
firstName: 'Joe',
lastName: 'Doe',
password: 'UOnlyMIbeu',
mobile: '09123456789',
email: 'test@gmail.com',
informationType: 'appointment',
appointment: [
{
appointmentNumber: 295693,
appointmentDate: 2022-04-16T04:00:00.000Z,
appointmentStatus: 'Pending'
}
]
}
>Solution :
Hope this works for you!
You have to use aggregation to match inside a document.
db.collection('users').aggregation([{ $match:
{ $and:
[
{ "$password": '123'},
{"$appointment.appointmentNumber":295693}
]
}
},
])