如何将此mongodb查询转换为C#驱动程序?

时间:2019-07-16 12:47:15

标签: c# mongodb mongodb-.net-driver

如何为此编写兼容的C#代码?

我知道我可以这样投影:

var projection = Builders<BsonDocument>.Projection.Include("title");

但是不知道如何在查找聚合后投影姓氏以获得作者的姓氏

db.books.aggregate(
   [
      {
         $project: {
            title: 1,
            lastName: "$author.lastName",
         }
      }
   ]
)

2 个答案:

答案 0 :(得分:0)

尝试这个

            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 
            }

答案 1 :(得分:-1)

假设您的作者实体嵌入在书本实体内部,这是一个强类型化的解决方案。如果您的作者是被引用的实体,请告诉我,我会更新答案。

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()作为官方驱动程序即可。