[英]How can i translate this mongodb query to c# driver?
我如何為此編寫兼容的C#代碼?
我知道我可以這樣投影:
var projection = Builders<BsonDocument>.Projection.Include("title");
但是不知道如何在查找聚合后投影姓氏以獲得作者的姓氏
db.books.aggregate(
[
{
$project: {
title: 1,
lastName: "$author.lastName",
}
}
]
)
試試這個
var project = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"title", 1},
{"lastName", "$author.lastName"},
}
}
};
var pipelineLast = new[] { project };
var resultLast = db.books.Aggregate<BsonDocument>(pipelineLast);
var matchingExamples = await resultLast.ToListAsync();
foreach (var example in matchingExamples)
{
// Display the result
}
假設您的作者實體嵌入在書本實體內部,那么這是一個強類型化的解決方案。 如果您的作者是被引用的實體,請告訴我,我將更新答案。
using MongoDB.Entities;
using System;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class Book : Entity
{
public string Title { get; set; }
public Author Author { get; set; }
}
public class Author
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
(new Book
{
Title = "a book title goes here",
Author = new Author
{
FirstName = "First Name",
LastName = "Last Name"
}
}).Save();
var res = DB.Queryable<Book>()
.Select(b => new
{
Title = b.Title,
LastName = b.Author.LastName
}).ToArray();
foreach (var b in res)
{
Console.WriteLine($"title: {b.Title} / lastname: {b.LastName}");
}
Console.Read();
}
}
}
上面的代碼使用我的MongoDB.Entities庫來簡化。 只需將DB.Queryable<Book>()
替換為官方驅動程序的collection.AsQueryable()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.