0

I have collection named "report" like this:

{ "_id" : ObjectId("5fc51722d6827f3bfd24e3b0"), "is_deleted" : false, "reporter" : ObjectId("5fb7b85f516b9709af5c7bc2"), "violator" : ObjectId("5fb8a07e9cd2840f5f6bac5a"), "reportNote" : "vi pham", "status" : 0, "createdAt" : ISODate("2020-11-30T16:00:34.013Z"), "updatedAt" : ISODate("2020-11-30T16:00:34.013Z"), "__v" : 0 } 

With "reporter" and "violator" is ObjectID that reference from "User" collection Now I want to find a list of violator and re-oder it from larger to small, so I do like this.

db.report.aggregate([ { $group: { _id: "$violator", count: { $sum: 1 } } }, { $sort: { count: -1 } } ]) 

And I have result as below.

{ "data": [ { "_id": "5fb8a07e9cd2840f5f6bac5a", "count": 10 }, { "_id": "5fbcbe855e26df3af08ffcee", "count": 7 }, { "_id": "5fbcb990cb35042db064b2b0", "count": 6 } ], "total": 23, "message": "" } 

My expected result is

{ "data": [ { "_id": "5fb8a07e9cd2840f5f6bac5a", "name": "David", "email": "[email protected]", "count": 10 }, { "_id": "5fbcbe855e26df3af08ffcee", "name": "Vincent", "email": "[email protected]", "count": 7 }, { "_id": "5fbcb990cb35042db064b2b0", "name": "robert", "email": "[email protected]", "count": 6 } ], "total": 23, "message": "" } 

I did follow turivishal recommend.

 db.report.aggregate([ { $group: { _id: "$violator", count: { $sum: 1 } } }, { $sort: { count: -1 } }, { $lookup: { from: "users", localField: "violator", foreignField: "_id", as: "ViolatorDetail" } } ]) 

But the result of ViolatorDetail (User) is empty.

{ "data": [ { "_id": { "violator": "5fb8a07e9cd2840f5f6bac5a", "status": 0, "reportNote": "vi pham" }, "count": 10, "ViolatorDetail": [] }, { "_id": { "violator": "5fbcbe855e26df3af08ffcee", "status": 0, "reportNote": "vi pham" }, "count": 7, "ViolatorDetail": [] }, { "_id": { "violator": "5fbcb990cb35042db064b2b0", "status": 0, "reportNote": "vi pham" }, "count": 6, "ViolatorDetail": [] } ], "total": 23, "message": "" } 
10
  • Does this answer your question? how to use populate and aggregate in same statement? Commented Dec 3, 2020 at 7:14
  • Thanks for reply but I did not find the answer in my question. Commented Dec 3, 2020 at 7:34
  • @cauchuyennhocuatoi your question is not clear, can you elaborate and add expected result. Commented Dec 3, 2020 at 7:51
  • @turivishal: Sorry for my english, I already edit my question and my expected result. Please take a look Commented Dec 3, 2020 at 8:15
  • just do $lookup after $sort stage and $unwind that lookup result. Commented Dec 3, 2020 at 8:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.