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

368
Visualizações
Using MongoDB .findOne() function with nested document value

Consider I have this document in my MongoDB collection, Workout:

{
  _id: ObjectId("60383b491e2a11272c845749") <--- Workout ID
  user: ObjectId("5fc7d6b9bbd9473a24d3ab3e") <--- User ID
  exercises: [
    {
      _id: ObjectId("...") <--- Exercise ID
      exerciseName: "Bench Press",
      sets: [
        {
          _id: ObjectId("...") <--- Set ID
        },
        {
          _id: ObjectId("...") <--- Set ID
        }
      ]
    }
  ]
}

The Workout object can include many exercise objects in the exercises array and each exercise object can have many set objects in the sets array. I am trying to implement a delete functionality for a certain set. I need to retrieve the workout that the set I want to delete is stored in. I have access to the user's ID (stored in a context), exercise ID and the set ID that I want to delete as parameters for the .findOne() function. However, I'm not sure whether I can traverse through the different levels of arrays and objects within the workout object. This is what I have tried:

const user = checkAuth(context) // Gets logged in user details (id, username)
const exerciseID, setID // Both of these are passed in already and are set to the appropriate values

const workoutLog = Workout.findOne({
  user: user.id,
  exercises: { _id: exerciseID }
});

This returns an empty array but I am expecting the whole Workout object that contains the set that I want to delete. I would like to omit the exerciseID from this function's parameters and just use the setID but I'm not sure how to traverse through the array of objects to access it's value. Is this possible or should I be going about this another way? Thanks.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

When matching against an array, if you specify the query like this:

{ exercises: { _id: exerciseID } }

MongoDB tries to do an exact match on the document. So in this case, MongoDB would only match documents in the exercises array of the exact form { _id: ObjectId("...") }. Because documents in the exercises have other fields, this will never produce a match, even if the _ids are the same.

What you want to do instead is query a field of the documents in the array. The complete query document would then look like this:

{
  user: user.id,
  "exercises._id": exerciseID
}
over 4 years ago · Santiago Trujillo Relatório

0

You can perform both find and update in one step. Try this:

db.Workout.updateOne(
    {
        "user": ObjectId("5fc7d6b9bbd9473a24d3ab3e"),
    },
    {
        $pull: {
            "exercises.$[exercise].sets": {
                "_id": ObjectId("6039709fe0c7d52970d3fa30") // <--- Set ID
            }
        }
    },
    {
        arrayFilters: [
            {
                "exercise._id" : ObjectId("6039709fe0c7d52970d3fa2e") // <--- Exercise ID
            }
        ]
    }
);
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