Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
How to do a find query for in an array of objects that displays all key-value from the parent schema and a specific object in the child schema?

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'
    }
  ]
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Hope this works for you!

You have to use aggregation to match inside a document.

db.collectionName.aggregate([
            {$unwind:{path:'$appointment'}},
            { $match:
                    { $and:
                       [
                         { "password": 'UOnlyMIbeu'},
                         {"appointment.appointmentNumber":295693}
                       ]
                 }
              },
])
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda