请问mongodb如何进行分组查询(不是分组聚合)

各位好 我的mongo一个表里有个字段是 serviceType,我仅仅想把相同的serviceType数据合起来一起显示,但我查了一些文章都是做分组聚合。所以我想问一下如何通过一个字段,把相同字段的列数据都放在一起统一显示。谢谢

阅读 2.4k
1 个回答

'把相同字段的列数据放在一起显示'

我不知道这样做是不是符合条件,效果应该是达到了一点

以下是根据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
      }
    ]
  }
]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进