使用其他字段从集合中获取不同的值

时间:2017-11-10 14:20:53

标签: node.js mongodb mongoose

我有这个查询从我的集合中返回不同的测试ID

Model.find().distinct('TestId', (err, data) => { console.log(data); }
  

[1,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]

这些所有值都有TestName,现在我也要返回它们。像这样:

  

[{TestId:1,TestName:' tname'} ...]

我该怎么做?

1 个答案:

答案 0 :(得分:1)

-save不支持在输出中添加其他字段,但您可以使用简单的distinct管道执行此操作:

aggregate

这会按Model.aggregate([{$group: {_id: '$TestId', TestName: {$first: '$TestName'}}}]) 对文档进行分组,并在每个组的第一个文档中包含TestId字段。