MongoDb C# Typed Aggregations with Group Unwind and Project

前端 未结 2 801
孤城傲影
孤城傲影 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()
                                      .Where(r => r.PersonInventory.Any())
                                      .SelectMany(r => r.PersonInventory)
                                      .Distinct()
                                      .ToArray();
            }
        }
    }
    

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

提交回复
热议问题