【问题标题】:How to get all documents and its count with mongoose如何使用猫鼬获取所有文件及其计数
【发布时间】:2021-02-02 18:54:38
【问题描述】:

我有一个模型叫 car 这个模型有 21 个文档

但我想要

  • 获取与 ma​​ke 属性匹配的所有文档数
  • 并创建具有 count 属性及其文档的新对象数组

例子

型号

const Car = new Schema({
  make: {
    type: String,
    required: true,
  },
  model: {
    type: String,
    required: true,
  },
  year: {
    type: Number,
    required: true,
  },
  fuelType: {
    type: String,
    required: true,
  },
  kilometers: {
    type: Number,
    required: true,
  },
  details: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  photoUrl: {
    type: String,
    required: true,
  },
});

我想获取所有具有这种形状的文档

const cars = [
  {
     make: 'Volkswagen',
     model: 'Tiguan',
     year: 2007,
     kilometers: 411019541855812,
     fuelType: 'Diesel',
     price: 14299,
     photoUrl: '/photos/cars/...jpg',
     details: 'Lorem ipsum..',
     count: 3
  },
  {
     ....
  }

]

最终目的是打印汽车“模型”及其数量

"Volkswagen Tiguan (5)"

【问题讨论】:

    标签: reactjs mongodb mongoose next.js mongoose-schema


    【解决方案1】:

    您可以使用聚合来执行此操作。

    Model.aggregate([
      {
        $match: {
          make: "Volkswagen"
        }
      },
      {
        "$group": {
          _id: {
            make: "$make",
            model: "$model"
          },
          count: {
            $sum: 1
          }
        }
      },
      {
        $project: {
          make: "$_id.make",
          model: "$_id.model",
          count: "$count",
          _id: 0
        }
      }
    ])
    

    这里首先我们filter基于make的文档,然后group基于makemodel的文档

    预期输出

    [
      {
        "count": 2,
        "make": "Company 1",
        "model": "Model 1"
      },
      {
        "count": 1,
        "make": "Company 1",
        "model": "Model 2"
      }
    ]
    

    【讨论】:

    • 感谢哥们的解决方案,我也解决了这个问题,只有 $group 和 $project 这样的 Car.aggregate([ { $group: { _id: "$make", count: { $sum : 1 }, 品牌: { $max: "$make" }, 模型: { $max: "$model" }, .... }, }, { $project: { _id: 0, make: 1, 模型: 1, 计数: 1, ..... }, }, ]);
    【解决方案2】:
        Cars.find({}).select("make model count").then(cars =>{
       cars.forEach(car =>{
              Console.log(car.make ,car.model , car.count)
         })
    })
    

    好吧,从您的输出来看,我相信您只需要制造、模型和计数。所以我添加了选择属性。如果你想检索你车的所有属性,那么你可以从上面删除选择属性

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 2017-04-09
      • 2014-05-30
      • 1970-01-01
      • 2018-10-13
      相关资源
      最近更新 更多