如何在TypeForm中处理mongodb聚合字段

如何在TypeForm中处理mongodb聚合字段,mongodb,typeorm,Mongodb,Typeorm,this.repo是一个MongoRepository,我想使用一个聚合管道来计算: this.repo.aggregateEntity([{ $group: { _id: {country: "$country"}, country: {$first: "$country"}, count: {$sum: 1} } }]) 我再也找不到计数字段。因此,我尝试了很多方法,例如,按照建议将count列添加到实体定义中

this.repo是一个MongoRepository,我想使用一个聚合管道来计算:

this.repo.aggregateEntity([{
      $group: {
        _id: {country: "$country"},
        country: {$first: "$country"},
        count: {$sum: 1}
      }
    }])
我再也找不到计数字段。因此,我尝试了很多方法,例如,按照建议将count列添加到实体定义中,而不使用元数据:

  ...
  @Index()
  @Column()
  country: string;

  count: number;
  ...
什么都没用。 如何获取结果中的count字段?

对集合执行聚合框架管道。这将按原样返回每个结果

MongoRepository.aggregateEntity
对集合执行聚合框架管道。这将返回游标的修改版本,该版本将每个结果转换为
实体
模型。如果您的
实体
模型没有结果字段,则不会填充该字段

//https://github.com/typeorm/typeorm/blob/51b2a63d/src/repository/MongoRepository.ts#L130
return this.manager.aggregateEntity(this.metadata.target, pipeline, options);

尝试执行
.aggregate
而不是
.aggregateEntity
您可以共享集合吗?@Valijon-太好了,我不知道。aggregate。非常感谢,这很有效。如果你愿意在这里回答,我可以把你的答案标记为已接受的答案。