3

Хочу сделать статистику регистрации юзеров в виде подобного графика: График

Каким образом мне получить количество записей за каждый день на протяжении месяца?

Что-то вроде:

2019-03-22 - 1

2019-03-23 - 10

...

Данные в таком виде:

{ 
   "name" : "Alexander",
   "createdAt" : ISODate("2019-03-22T11:04:19.709Z"), 
   "updatedAt" : ISODate("2019-04-29T10:22:51.953Z")
}
1

1 ответ 1

2

Я написал это в mongo shell, в код на mongoose, думаю, сами сможете перевести

map = function(){
    emit(
        Date.UTC(
            this.createdAt.getFullYear(), 
            this.createdAt.getMonth(), 
            this.createdAt.getDate()
), this.name)};

const reduce = function(key, value){return value.length};
db.users.mapReduce(map, reduce, { out: {inline: 1} });

либо через aggregate

db.users.aggregate([{$group: {_id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }, users: {$push: "$name"}}}, {$project: {usersCount: {$size: "$users"}}}])
4
  • 1
    наверное под задачу лучше подходит map = function(){emit(Date.UTC(this.createdAt.getFullYear(), this.createdAt.getMonth(), this.createdAt.getDate()), this.name)}; 29 сен 2020 в 16:54
  • 2
    да, конечно, забыл что там ещё и время 29 сен 2020 в 16:56
  • 1
    или даже ${this.createdAt.getFullYear()}-${1+this.createdAt.getMonth()}-${this.createdAt.getDate()}. поправь ответ, короч ) 29 сен 2020 в 16:57
  • Спасибо большое 29 сен 2020 в 17:07

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.