MongoDB的push和root的C#等效项是什么? [英] What is the C# equivalent of push and root for MongoDB?
问题描述
我有很多人.我正在尝试为每个名字找到年龄最大的人.我可以使用mongoDB控制台命令实现该结果
I have a collection of people. I am trying to find the oldest person for each name. I am able to achieve that result using the mongoDB console command
db.People.aggregate([
{ '$sort': { 'Name': 1, 'Age': -1 } },
{
'$group': {
'_id': '$Name',
'docs': { '$push': '$$ROOT' },
}
},
{
'$project': {
'top_one': {
'$slice': ['$docs', 1]
}
}
} ])
对于C#驱动程序,这等效于什么?我特别遇到麻烦了
What is the equivalent of this for the C# driver? I'm specifically having trouble with
'docs': { '$push': '$$ROOT' },
这是我当前的C#查询:
Here is my current C# query:
collection.Aggregate(aggArgs)
.SortByDescending(x => x.Age)
.Group(x => x.Name, x => new {
Name = x.First().Name,
FavoriteColor = x.First().FavoriteColor,
FavoriteFood = x.First().FavoriteFood
}).ToListAsync().Result;
它的工作原理与我的mongo console命令差不多,但是我真的不喜欢构造匿名对象.我更愿意做Group(x => x.Name,x => x.First())
,但是会抛出异常,并且不支持"First()".我相信部分问题是我的Person类型没有ID,因此_id放在实际的mongo文档中(插入时由mongo自动执行).当它尝试返回该类型时,无法进行直接映射.
It works close to what my mongo console command does, but I really don't like constructing an anonymous object. I would prefer to do Group(x => x.Name,x => x.First())
, but that throws and exceptions that "First()" is not supported. I believe part of the problem is that is that my Person type doesn't have an ID, so _id is put on the actual mongo document (automatically by mongo on insert). When it trys to go back in to the type, it can't do a direct mapping.
因此,考虑到两个版本的查询,如何在不使用每个字段拼写的情况下将我的完整类型恢复为C#?
So, with the two versions of the query in mind, how do I get my full type back in C# without having to spell out EVERY field?
推荐答案
这是MongoDB驱动程序的功能.它不接受简单的First(),它后面需要一些东西.那就是我通过调试看到的.因此,您应该继续使用First()...,也可以直接查询json:
It's a feature of MongoDB driver. It doesn't accept simple First(), it need something behind it. That was what i have seen by debugging. So you should either continue to work with First()... or you could query your json directly:
var result = collection.Aggregate()
.Group(new JsonProjectionDefinition<People>(@" {
'_id': '$Name',
'docs': { '$push': '$$ROOT' },}"))
.Project<TopOne>(new JsonProjectionDefinition<BsonDocument>(@"{
'top_one': {
'$slice': ['$docs', 1]
} }"))
.ToList();
这篇关于MongoDB的push和root的C#等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!