我如何将此 mongodb 查询转换为 C# 驱动程序?
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 Whosebug
{
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()
。
我如何为此编写兼容的 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 Whosebug
{
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()
。