Mongodb find() 查询:仅返回唯一值(无重复)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28155857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:16:03  来源:igfitidea点击:

Mongodb find() query : return only unique values (no duplicates)

mongodbmongodb-query

提问by Franckl

I have a collection of documents :

我有一组文件:

{
    "networkID": "myNetwork1",
    "pointID": "point001",
    "param": "param1"
}
{
    "networkID": "myNetwork2",
    "pointID": "point002",
    "param": "param2"
}
{
    "networkID": "myNetwork1",
    "pointID": "point003",
    "param": "param3"
}
...

pointIDs are unique but networkIDs are not.

pointID 是唯一的,但 networkID 不是。

Is it possible to query Mongodb in such a way that the result will be : [myNetwork1,myNetwork2]

是否可以以这样的方式查询 Mongodb,结果将是:[myNetwork1,myNetwork2]

right now I only managed to return [myNetwork1,myNetwork2,myNetwork1]

现在我只能返回 [myNetwork1,myNetwork2,myNetwork1]

I need a list of unique networkIDs to populate an autocomplete select2 component. As I may have up to 50K documents I would prefer mongoDb to filter the results at the query level.

我需要一个唯一的 networkID 列表来填充自动完成 select2 组件。由于我可能有多达 50K 个文档,我更喜欢 mongoDb 在查询级别过滤结果。

回答by Laura Uzcategui

I think you can use db.collection.distinct(fields,query)

我想你可以用 db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

您将能够在您的案例中为 NetworkID 获得不同的值。

It should be something like this :

它应该是这样的:

Db.collection.distinct('NetworkID')