MongoDB 将 Node.js 中的聚合查询转换为 LINQ

问题描述 投票:0回答:1

我在 node.js 中有一个聚合查询,我正在努力将其转换为 LINQ。 这是原版

const books = await collection.aggregate()
    .group({
        _id: "$author",
        count: { $sum: 1 },
        return_date: { $last: "$return_date" },
        title: { $last: "$title" },
    })
    .sort({ count: -1, _id: 1 })
    .limit(20).toArray();

迄今为止我能做的最好的事情是

IMongoQueryable<Popular> query = (from book in booksCollection.AsQueryable()
                                  group book by book.author into g
                                  select new Popular
                                  {
                                      Author = g.Key,
                                      Count = g.Count()
                                  }).OrderByDescending(g => g.Count).ThenBy(g => g.Author).Take(20);

人气在哪里

 public class Popular
 {
     public string? Title { get; set; } = null;
     public string? Author { get; set; } = null;
     public string? ReturnDate { get; set; } = null;
     public int? Count { get; set; }
 }

我找不到包含 ReturnDate 和 Title 的方法,因此我必须对每个结果进行额外的查询才能添加这些字段。有没有更优雅的方法来转换此查询?

node.js mongodb linq
1个回答
0
投票

您可以使用 LINQ 的 GroupBy 和投影功能在单个 LINQ 查询中获取 ReturnDate 和 Title,而无需触发额外的查询

IMongoQueryable<Popular> query = (from book in booksCollection.AsQueryable()
                                  group book by book.Author into g
                                  let lastBook = g.OrderByDescending(b => b.ReturnDate).FirstOrDefault()
                                  select new Popular
                                  {
                                      Author = g.Key,
                                      Count = g.Count(),
                                      ReturnDate = lastBook.ReturnDate,
                                      Title = lastBook.Title
                                  })
                                  .OrderByDescending(g => g.Count)
                                  .ThenBy(g => g.Author)
                                  .Take(20);
© www.soinside.com 2019 - 2024. All rights reserved.