Home > Blockchain >  Return only a subdocument from document in mongoose
Return only a subdocument from document in mongoose

Time:04-01

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?

CodePudding user response:

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 .

CodePudding user response:

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

  • Related