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

129
Visualizações
Return only a subdocument from document in mongoose

I am working on an app that uses MongoDB (I use Mongoose) as its database.

I have a question, suppose I have this kind of schema:

[{
  "user_id":"2328292073"
  "username":"Bob",
  "subscriptions":[
    {
      "id":"38271281,
      "payments":[
        {
          "id":"00001",
          "amount":"1900"
        },
         {
          "id":"00002",
          "amount":"2000"
        },
         {
          "id":"00003",
          "amount":"3000"
        }
      ]
    }
  ]

}]

In my case I want to get the payments array for subscription with id = '38271281' of user with id '2328292073', but I just want to retrieve the payment array, nothing else

My query is the following:

Mongoose.findOne({
  "user_id": "2328292073",
  "subscriptions.id": "38271281"
},
{
  "subscriptions.payments": 1
})

But I get the entire document of subscriptions. How can i get the payment array only?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you can try using unwind if you want filteration from db only.


Mongoose.aggregate([
  {
    '$match': {
      'user_id': '2328292093'
    }
  }, {
    '$unwind': {
      'path': '$subscriptions'
    }
  }, {
    '$match': {
      'subscriptions.id': '38271281'
    }
  }
])

if you will have multiple documents having same subscription id then you have to group it .

  • using code level filter function can also be one another approach to do this .
about 4 years ago · Juan Pablo Isaza Relatório

0

You can try aggregation operators in projection in find method or also use aggregation method,

  • $reduce to iterate loop of subscriptions and check the condition if id matched then return payment array
db.collection.find({
  "user_id": "2328292073",
  "subscriptions.id": "38271281"
},
{
  payments: {
    $reduce: {
      input: "$subscriptions",
      initialValue: [],
      in: {
        $cond: [
          { $eq: ["$$this.id", "38271281"] },
          "$$this.payments",
          "$$value"
        ]
      }
    }
  }
})

Playground

about 4 years ago · Juan Pablo Isaza 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