我有一个包含这些字段的表(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();
如何获得不同的用户名?
答案 0 :(得分:3)
// .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查询方法。
为了获得更好的独特使用效果:
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();
.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" } }
])