How does MongoDB sort and sequence within a group?

  mongodb, question

For example:
{“behavior” : “S_0004”, “createTime” : “2019-03-17 22:52:35”, “userId” : “800202”},
{“behavior” : “S_0009”, “createTime” : “2019-03-17 20:40:42”, “userId” : “800202”},
{“behavior” : “S_0056”, “createTime” : “2019-03-17 09:31:22”, “userId” : “800200”},
{“behavior” : “S_0050”, “createTime” : “2019-03-17 09:31:30”, “userId” : “800200”}
To group by userId, the group is sorted in ascending order by createTime, and a sorted field is added to get:
{“userId” : “800202”, “behavior” : “S_0009”, “sort” : 1},
{“userId” : “800202”, “behavior” : “S_0004”, “sort” : 2},
{“userId” : “800200”, “behavior” : “S_0056”, “sort” : 1},
{“userId” : “800200”, “behavior” : “S_0050”, “sort” : 2}
How should this be written? I just got started and haven’t written it for a long time. …

At present, there is no such way to add serial numbers, but this is not a necessary requirement and will only make it more convenient for you to use. In fact, as long as the grouping is available, the sequence number can be completely generated at the program side. If you don’t consider the problem of serial number, then it is very simple, even without grouping, and without grouping will actually be more efficient:

db.coll.find({}, {
 _id: 0,
 userId: 1,
 behavior: 1
 }).sort({
 userId: 1,
 createTime: 1
 });

This query is more efficient when it has the following indexes:

db.coll.createIndex({userId: 1, createTime: 1});