MongoDb C# Typed Aggregations with Group Unwind and Project

走远了吗. 提交于 2019-12-01 08:38:39

this can be easily achieved with the IMongoQueryable interface like shown below

using MongoDB.Entities;
using System.Linq;

namespace StackOverflow
{
    public class RootDoc : Entity
    {
        public Person[] PersonInventory { get; set; }
    }

    public class Person
    {
        public long PersonId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class Program
    {
        private static void Main(string[] args)
        {
            new DB("test");

            (new[] {
                new RootDoc{
                    PersonInventory = new[]{
                        new Person{ PersonId = 1, FirstName = "first", LastName="person"},
                        new Person{PersonId = 2, FirstName = "second", LastName="person"}
                    }
                },
                new RootDoc{
                    PersonInventory = new[]{
                        new Person { PersonId = 2, FirstName = "second", LastName = "person" } }
                }
            }).Save();

            var uniquePersons = DB.Queryable<RootDoc>()
                                  .Where(r => r.PersonInventory.Any())
                                  .SelectMany(r => r.PersonInventory)
                                  .Distinct()
                                  .ToArray();
        }
    }
}

above code uses my library MongoDB.Entities for brevity. just replace DB.Queryable<RootDoc>() with collection.AsQueryable() for official driver.

I did some digging on the mongodb Jira pages, it looks like there isn't support for the variable $$ROOT, so the above queries are not supported.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!