Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

how to group by string pattern (not necessarily regex) in mongoDB aggregation

I have a dataset in the collection with following schema:

[
    {"status": "Completed", "datetime_field": "2021-01-01T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Completed", "datetime_field": "2021-01-02T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "New", "datetime_field": "2021-01-02T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Cancelled - type 0", "datetime_field": "2021-01-01T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Draft", "datetime_field": "2021-01-03T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Completed", "datetime_field": "2021-01-01T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Cancelled - type 1", "datetime_field": "2021-01-04T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Cancelled - type 2", "datetime_field": "2021-01-01T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Deleted", "datetime_field": "2021-01-05T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Completed", "datetime_field": "2021-01-01T00:00:00.000Z", "aother_field_key": "aother_field_values"},
    {"status": "Completed", "datetime_field": "2021-01-01T00:00:00.000Z", "aother_field_key": "aother_field_values"}
]

And I want to group by both datetime_field and status fields in mongoDB aggregation pipeline. I know that for the datetime field using $dateToString operator can easily control the granularity of grouping by datetime. The issue I'm having is to group by the status.

As you can see there are more than one type of Cancelled status, if simply do {$group: {_id: {status: '$status'}}} it will separate the different types of Cancelled, is there a way to group all different types of Cancelled into one group?

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...