1

I need to join 3 collections and get the desired data. I have written a LINQ query which working fine but I want to write it using mongoDb's Aggregate interface. Here is my query in LINQ.

 var query = from user in userCollection.AsQueryable()
                        where user.Id == userId
                        from userDivision in user.Divisions
                        select new { userDivision.DivisionId } into divisions
                        join division in divisionCollection.AsQueryable() on divisions.DivisionId equals division.Id
                        select new { division.CompanyId } into divisionCompany
                        join company in companyCollection.AsQueryable() on divisionCompany.CompanyId equals company.Id
                        select new
                        {
                            company.Id,
                            company.Code,
                            company.Name,
                            company.Address,
                            ConcurrencyId = "1_" + "3_" + company.Id
                        } into c
                        join concurrency in concurrencyCollection.AsQueryable() on c.ConcurrencyId equals concurrency.Id into concurrencies
                        from concurrencyEmpty in concurrencies.DefaultIfEmpty()
                        select new Response.Company
                        {
                            Id = c.Id,
                            Code = c.Code,
                            Name = c.Name,
                            CodeAndName = c.Code + " - " + c.Name,
                            Address = c.Address,
                            ConcurrencyVersion = concurrencyEmpty.Version
                        };

Can anybody tell me how to write this query using MongoDb's aggregate interface (using LookUp etc).

Thanks in advance.

  • You can use aggregation [$lookup](https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/) for "join" operations on multiple collections. – prasad_ Jun 30 '21 at 09:31
  • see this https://stackoverflow.com/questions/36019713/mongodb-nested-lookup-with-3-levels and this https://stackoverflow.com/questions/35638372/how-to-lookup-with-mongodb-c-sharp-driver – dododo Jul 08 '21 at 13:16

0 Answers0