Lo siento si el título es confuso porque todavía estoy aprendiendo a codificar. Aquí está mi código pero muestra todos los objetos en la matriz. Solo quiero que se muestre un objeto específico del esquema secundario mientras se muestra todo el valor clave en el padre.
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 + "." }); } })Esta es la salida del código anterior:
{ _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' } ] }Y esto es lo que quiero que suceda:
{ _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' } ] }¡Espero que esto funcione para usted!
Debe usar la agregación para hacer coincidir dentro de un documento.
db.collectionName.aggregate([ {$unwind:{path:'$appointment'}}, { $match: { $and: [ { "password": 'UOnlyMIbeu'}, {"appointment.appointmentNumber":295693} ] } }, ])