猫鼬:返回没有重复条目的唯一结果集

Mongoose: Returning unique result set with no duplicate entries

我在 MEAN 环境中使用 Mongoose。我如何确保我的结果集中没有任何重复的结果? 示例:我的数据库包含 10 个(部分重复的)名称:

当查询此数据库的 'Allan' 或什至 'all' 时(使用 .find(regex...) 并将返回结果的数量限制为 5,我得到这个:

'Allan' 的三个重复条目,我们浪费了很多结果多样性(谈论搜索输入字段的自动完成功能)。我需要返回的结果集不重复,比如:

如果有的话,如何使用 mongoose 实现?

您可以使用 MongoDB 的 distinct() query to find only distinct values (i.e., unique) in your set. Per the API docs,distinct 可以与 Mongoose 一起使用。

他们的例子:

{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }

有了db.inventory.distinct( "dept" )就会return[ "A", "B" ]

您可以使用此处建议的方法过滤数组形式的搜索结果:

Delete duplicate from Array

您可以使用 find 建立查询,然后在生成的查询对象上链接对 distinct 的调用以获取结果中的唯一名称:

var search = 'Allan';
Name.find({name: new RegExp(search)}).distinct('name').exec(function(err, names) {...});

或者您可以将它们全部合并到模型上对 distinct 的调用中,提供查询对象作为第二个参数:

var search = 'Allan';
Name.distinct('name', {name: new RegExp(search)}, function(err, names) {...});

在这两种情况下,names 只是不同名称的数组,而不是完整的文档对象。

您也可以使用 aggregate 执行此操作,这样您就可以直接限制结果的数量:

Name.aggregate([
    {$match: {name: new RegExp(search)}},
    {$group: {_id: '$name'}},
    {$limit: 5}
])