MongoDb C# Typed Aggregations with Group Unwind and Project

前端 未结 2 800
孤城傲影
孤城傲影 2021-01-14 07:10

I have a collection like this:

[{
  \"_id\": 1,
  \"OtherProperties\": 100
  \"PersonInventory\": [{
    \"FirstName\": \"Joe\",
    \"MiddleName\": \"Bob\",         


        
相关标签:
2条回答
  • 2021-01-14 07:56

    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.

    0 讨论(0)
  • 2021-01-14 08:15

    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.

    0 讨论(0)
提交回复
热议问题