Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!