Fork me on GitHub

mongodb 根据某个字段对文档进行分组查询

根据某个字段进行分组查询,值相同的在同一组,不进行聚合操作

可执行代码(根据字段serviceType进行分组查询):

const mongoose = require('mongoose')
const fs = require('fs')

mongoose.connect('mongodb://localhost/test', { useUnifiedTopology: true, useNewUrlParser: true })
const Temp = mongoose.model('User', new mongoose.Schema({
  name: String,
  serviceType: String
}), 'test_temp');
(async function () {
  await Temp.deleteMany({})
  await new Temp({ name: '嘎嘎123', serviceType: 1 }).save()
  await new Temp({ name: '嘎嘎321', serviceType: 1 }).save()
  await new Temp({ name: '嘎321嘎', serviceType: 2 }).save()
  await new Temp({ name: '嘎321嘎', serviceType: 3 }).save()
  await new Temp({ name: '嘎嘎132', serviceType: 2 }).save()
  const res = await Temp.aggregate([
    {
      $group: {
        _id: '$serviceType',
        arr: { $push: "$$ROOT" }
      }
    }]
  )
  fs.writeFileSync('./res.json', JSON.stringify(res))
  mongoose.disconnect()
}()).catch(err => {
  console.error(err)
  mongoose.disconnect()
})

输出:

[
  {
    "_id": "2",
    "arr": [
      {
        "_id": "5dce54f86dffa845bc4d3a76",
        "name": "嘎321嘎",
        "serviceType": "2",
        "__v": 0
      },
      {
        "_id": "5dce54f86dffa845bc4d3a78",
        "name": "嘎嘎132",
        "serviceType": "2",
        "__v": 0
      }
    ]
  },
  {
    "_id": "3",
    "arr": [
      {
        "_id": "5dce54f86dffa845bc4d3a77",
        "name": "嘎321嘎",
        "serviceType": "3",
        "__v": 0
      }
    ]
  },
  {
    "_id": "1",
    "arr": [
      {
        "_id": "5dce54f86dffa845bc4d3a74",
        "name": "嘎嘎123",
        "serviceType": "1",
        "__v": 0
      },
      {
        "_id": "5dce54f86dffa845bc4d3a75",
        "name": "嘎嘎321",
        "serviceType": "1",
        "__v": 0
      }
    ]
  }
]