0

I have a mongo collection named feetransaction that contain batch wise transaction record of students.

Since a student can make multiple payments, each student can have multiple transaction records.

I want to get last feetransaction record for each student for requested batch in a single query. My mongo domain is as follows:

{
        "_id" : ObjectId("56e0ce6ba094a91976e708b6"),
        "studentId" : "56e0ce6aa094a91976e7048e",
        "studentName" : "XYZ",
        "batchId" : "56e0ce6aa094a91976e70003",
        "batchName" : "10 - A",
        "payableAmount" : 200,
        "paid" : 850,
        "prevBal" : 0,
        "balance" : -650,
        "createdDate" : ISODate("2016-03-10T01:31:22.505Z") 
} 
{
        "_id" : ObjectId("56e0ce6ba094a91976e708b6"),
        "studentId" : "56e0ce6aa094a91976e7048e",
        "studentName" : "ABC 1",
        "batchId" : "56e0ce6aa094a91976e70003",
        "batchName" : "10 - A",
        "payableAmount" : 200,
        "paid" : 850,
        "prevBal" : 0,
        "balance" : -650,
        "createdDate" : ISODate("2016-03-10T01:31:22.505Z") 
}
kalyani
  • 23
  • 4
  • [`$last`](https://docs.mongodb.org/manual/reference/operator/aggregation/last/) is actually the top search result for your very question tile – Blakes Seven Mar 11 '16 at 03:29
  • Make sure you have valid documents. Sample document you posted above are not valid as they have duplicate key `_id` – Saleem Mar 11 '16 at 03:43
  • @Saleem It's clearly just "copy/paste" with an altered "createdDate". Most people viewing would work that out since it simply is not possible to have the same value in the `_id` primary key. It wasn't relevant anyway since the answer would have been imediately visable should the OP have done a search for what they wanted before posting. Operator is the top result, and the linked duplicate is just four results down ( would be three but for multiple manual page hits ). – Blakes Seven Mar 11 '16 at 04:45
  • @BlakesSeven, yes, I agree. Even createdDate are exactly same. no alteration. Both documents have same value `ISODate("2016-03-10T01:31:22.505Z")` – Saleem Mar 11 '16 at 04:58

0 Answers0