LoginSignup
1
0

More than 5 years have passed since last update.

mongooseでの集計(aggregate , group , sum)

Last updated at Posted at 2018-10-03

前提

サンプルソース

mongoose-aggregate.js
// Mongoose aggreagate の例
// <参考>
// https://garafu.blogspot.com/2018/01/mongodb-group-by-sum.html
require('../../config/config.js')
require("../../db/mongoose.js");
const {SampleOrder} = require("../../models/sampleorder.js")

//サンプルデータ定義
const orders =[
  { datetime: Date.parse("2017-12-15T12:00:00+09:00"), item: "pen", amount: 70 },
  { datetime: Date.parse("2017-12-15T12:00:00+09:00"), item: "note", amount: 40 },
  { datetime: Date.parse("2017-12-15T12:00:00+09:00"), item: "eraser", amount: 100 },
  { datetime: Date.parse("2017-12-12T12:00:00+09:00"), item: "note", amount: 80 },
  { datetime: Date.parse("2017-12-08T12:00:00+09:00"), item: "eraser", amount: 50 },
  { datetime: Date.parse("2017-11-21T12:00:00+09:00"), item: "eraser", amount: 70 },
  { datetime: Date.parse("2017-11-13T12:00:00+09:00"), item: "pen", amount: 20 },
  { datetime: Date.parse("2017-11-02T12:00:00+09:00"), item: "pen", amount: 40 },
  { datetime: Date.parse("2017-10-23T12:00:00+09:00"), item: "pen", amount: 30 },
  { datetime: Date.parse("2017-10-18T12:00:00+09:00"), item: "pen", amount: 10 },
]
//初期化
async function initSampleOrders(){
  await SampleOrder.deleteMany({})
  let res = await SampleOrder.insertMany(orders)
  console.log('[initSampleOrders] length:',res.length)
}
//集計
async function groupSum(){
  console.log('---method:',groupSum.name)
  const res = await SampleOrder.aggregate()
  .group({
    _id:'$item',
    total:{$sum:'$amount'},
  })
  console.log(res)
}
//Main
async function main() {
  console.log('*** start ***')
  await initSampleOrders()
  await groupSum()
  console.log('*** end ***')
}
main()

実行結果

*** start ***
[initSampleOrders] length: 10
---method: groupSum
[ { _id: 'note', total: 120 },
  { _id: 'eraser', total: 220 },
  { _id: 'pen', total: 170 } ]
*** end ***
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0