我的 MongoDB 中有多个具有这种结构的文档:
{
"_id" : ObjectId("56792b6898015712282264d5"),
"Stamp" : ISODate("2015-12-22T10:52:24.640+0000"),
"Key" : null,
"RoleTitle" : "SDE",
"StartDate" : ISODate("2014-08-01T07:00:00.000+0000"),
"EndDate" : null,
"Salary" : null,
"PayType" : null,
"Currency" : null
}
对于当前作业,结束日期字段设置为 null
我想从数据库中找到最近的工作,这就是我目前在 C# 中做的事情,它抛出 Null Pointer Exception 因为集合包含文档EndDate 为 null
:
var filter = Builders<WorkHistory>.Filter.Where(u => u.MemberOid == oid);
var doc = db.GetFilteredDocuments(filter).OrderByDescending(u => u.EndDate).FirstOrDefault();
如果 EndDate 为 null
,我还想按 StartDate 对这些文档进行排序。
我如何找到最近的工作?
最佳答案
最好避免那些允许您传递闭包的 API 方法(不确定它是否以某种方式转换为 Javascript 并在数据库上执行,或者过滤器是否在请求整个集合内容后在客户端执行,但这两种选择都很可怕)。在您的情况下,您作为 C# 函数实现的操作非常简单,并且由直接转换为 native MongoDB 功能的标准 API 涵盖:
代替 Filter.Where(function)
使用 Filter.Eq("field", value)
使用 .SetSortOrder(SortBy.Descending("field"))
代替 .OrderByDescending(function)
。
如果您遇到了原生 MongoDB 功能无法涵盖且绝对必须使用函数的罕见边缘情况之一,请以处理空值的方式编写您的函数。例如,这会将日期为 null
的每个字段视为公元 1 年 1 月 1 日的 00:00:00.000:
OrderByDescending(u => u.EndDate == null ? new DateTime(0) : u.EndDate)
关于c# - 如果可能存在空值,如何在 mongodb 中使用 orderby?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34415986/