查找某个时段中某个字段的明确值

时间:2014-10-15 15:23:14

标签: c# linq mongodb-.net-driver

我有一个包含这些字段的表(detecc):

 uname   string
 door    string
 dt      double (seconds since 1/1/1970)

我的查询效果很好:

double dt1= SeconsdSince1970(DateTime.Now);
double dt0= dt1 - 3600;
var doorSearch = new string[] { "D1", "D2" };
System.Int32 cNow = (from d in detecc
                     where doorSearch.Contains(d.door) &&
                     (d.dt >= dt0 && d.dt <= dt1)
                     select d.uname).Distinct().Count();

但如果我想检索用户(uname),我会得到所有记录(重复):

double dt1= SeconsdSince1970(DateTime.Now);
double dt0= dt1 - 3600;
var doorSearch = new string[] { "D1", "D2" };
var lisUname = (from d in detecc
                     where doorSearch.Contains(d.door) &&
                     (d.dt >= dt0 && d.dt <= dt1)
                     select d.uname).Distinct();

如何获得不同的用户名?

1 个答案:

答案 0 :(得分:3)

如果您正在使用mongodb集合,请尝试使用

// .ToList() converts to poco list
var lisUname = (from d in detecc
                     where doorSearch.Contains(d.door) &&
                     (d.dt >= dt0 && d.dt <= dt1)
                     select d.uname).ToList();

// distinct is now executed in c# context rather mongodb context
var distinctList = lisUname.Distinct();

更清晰的语法

var list = detecc
    .Where(d => doorSearch.Contains(d.door) && (d.dt >= dt0 && d.dt <= dt1)
    .Select(x => x.uname)
    .ToList();

性能

  

注意:.Select将始终结束您的查询并将所有数据(完整文档)传递给本机代码。因此,您从服务器和代码中获取完整数据,然后选择所需的字段。如果您只想提取请求的字段,则需要另一个mongodb查询方法。

     

Refer to Documentation on Linq driver

为了获得更好的独特使用效果:

var list = detecc
    .Where(d => doorSearch.Contains(d.door) && (d.dt >= dt0 && d.dt <= dt1)
    .Distinct() // that way distinct is executed on server side
    .ToList();

为什么用mongodb链接.Count()不起作用

  

.Count()意味着与自己的参数分开使用。   请参阅此文Why the MongoDB Count Property Returns All Records

// Example
int userCount = db.GetCollection("detecc")
        .Count(Query.EQ("uname", searchedUName));

一种更高效的聚合方法

对于更高效的方法,请使用mongodb aggretation,如

db.collection.aggregate([
    { "$match": { "$and": [ { "prop1": "" }, { "prop2": "" } ] } },
    { "$group": { "_id": "$messageId" } }  
])
  

请参阅此答案:MongoDb Distinct with query C# driver