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

Categories

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

javascript - group result using date from object keys and only get count the results

Hello I'm having a hard time getting this complex return using MongoDB nor Javascript. Hope can anyone teach me how to get this return.

Admin.

group result by id

user flatten result

Here's the data example.

let user = [
    {
  _id: 123,
  name: 'John',
  createdAt: "2015-08-12T00:00:00Z"
  },
  {
  _id: 124,
  name: 'Jane',
  createdAt: "2015-09-12T00:00:00Z"
  },
  {
  _id: 125,
  name: 'Robert',
  createdAt: "2015-09-12T00:00:00Z"
  },
  {
  _id: 126,
  name: 'Samson',
  createdAt: "2016-11-12T00:00:00Z"
  }
]

Expected Result

user

[
{
 "15-8": 1 //yyyy-mm: number of data for the month of august
},
{
 "15-9": 2
},
{
 "16-11": 1
}
]

admin

[
    {
     "15-8": 
   {
    _id: 123,
    count: 1
   }
    },
    {
     "15-9": {
     _id: 124,
     count: 1,
   },{
     _id: 125,
     count: 1
    },
    {
     "16-11": {
     _id: 126,
     count: 1
     }
    }
    ]
question from:https://stackoverflow.com/questions/65947873/group-result-using-date-from-object-keys-and-only-get-count-the-results

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

1 Reply

0 votes
by (71.8m points)
  1. You should have the function to get key from date string named getKeyFromDate with format result YY-MM

  2. Loop user data to aggregate your data by using reduce, for example.

let user = [
    {
      _id: 123,
      name: 'John',
      createdAt: "2015-08-12T00:00:00Z"
    },
    {
      _id: 124,
      name: 'Jane',
      createdAt: "2015-09-12T00:00:00Z"
    },
    {
      _id: 125,
      name: 'Robert',
      createdAt: "2015-09-12T00:00:00Z"
    },
    {
      _id: 126,
      name: 'Samson',
      createdAt: "2016-11-12T00:00:00Z"
    }
];

const getKeyFromDate = (dateString) => {
  var date = new Date(dateString);
  var year = date.getFullYear().toString().substr(2, 3);
  var month = date.getMonth() + 1;
  return `${year}-${month}`; // YY-MM
};

var result = user.reduce((acc, {createdAt}) => {
  var key = getKeyFromDate(createdAt);
  acc[key] = acc[key] || {[key]: 0}; //Also use shortcut like: acc[key] ??= {[key]: 0};
  acc[key][key] += 1;
  return acc; 
  
}, {});
console.log(Object.values(result));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...