[英]MongoDB - Query max date in collection
I've got a collection with a registeredtime
field and to query the latest insertion:我有一个带有registeredtime
时间字段的集合并查询最新插入:
db.orders.aggregate({ $group: { _id: 1, regt: { $max: "$registeredtime" }}})
Now I want to integrate this into a C# .NET Core MongoDB client but I'm completely stuck on this:现在我想将它集成到 C# .NET Core MongoDB 客户端,但我完全坚持这个:
var filter = _collection.Aggregate().Group( _id => ???? )
How to query the max time of a field in C# MongoDB client?如何查询C# MongoDB客户端中某个字段的最大时间?
Solution 1: With BsonDocument
解决方案 1:使用BsonDocument
BsonDocument groupStage = new BsonDocument
{
{ "_id", 1 },
{ "regt", new BsonDocument("$max", "$registeredtime") }
};
var result = await _collection.Aggregate()
.Group<BsonDocument>(groupStage)
.ToListAsync();
Demo演示
Solution 2: With Expression解决方案 2:使用表达式
Pre-requisites: Create a concrete class for the output result.先决条件:为 output 结果创建具体的 class。
class OrderGroup
{
public int Id { get; set; }
public DateTime Regt { get; set; }
}
var result = await _collectionAggregate()
.Group<Order, int, OrderGroup>(x => 1, x => new OrderGroup
{
Id = x.Key,
Regt = x.Max(y => y.Registeredtime)
})
.ToListAsync();
Demo演示
Sample Input Data样本输入数据
[
{
"registeredtime": new Date("2021-01-02T01:02:03Z")
},
{
"registeredtime": new Date("2022-09-02T00:00:00Z")
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.