$group by one parameter and get all data of it

Hello Everyone,

I am using the below query to group data by resource but I want all data in that particular resource how can I do that

    `var m = await model.aggregate([{$group : {_id: {resource : '$resource', project: '$project', reporting_to: '$reporting_to', remark: '$remark', occupancy: '$occupancy', status: '$status'}, count: { $sum: 1 }}}]);`

what I want is to group it by the resource : '$resource' and get all the items in that particular resource entry, in case with my above query its is showing all 6 entries but i dont want duplicated entry if there are two resource of same name so it should give me the latest one

Thank you in Advance
Juned Adenwalla,

@Juned_Adenwalla hi there!
I am not sure I understand, if this is not what you need, please include input documents (at least one) and expected output.

  $group: {
    _id: {
      key1: "$key1",
      key2: "$key2",
    all: {
      $push: "$$ROOT"

This groups from your collection documents with the same fields in _id. This is a low match, i.e, documents with those fields + extra fields would be grouped also. Hope that makes sense.

If that resonates, check out carefully this live example in MongoPlayground.

You can also append your accumulator field.

Thank you so much for your help sir, but fortunatly when i got this message I also found solution from google.

I used the code below

doc: { $first: "$$ROOT" }

thank you so much for your reply

I actually missed that, great that you found the right solution.

Note that using $first is only meaningful (and correct to get latest entry) if you guarantee your data is sorted by date descending - otherwise you’ll get whatever happens to be the first entry in some arbitrary order.