2

I am trying to transpose a MongoDb query into a C# Mongo Driver query. The purpose is to make a join between collections. I mention that in this case, nesting documents isn't an option.

So the following MongoDb query works as expected:

db.Orders.aggregate(
    [ {$lookup: {
        from: 'Status',
        localField: 'orderStatusId',
        foreignField: '_id',
        as: 'status'
      }}, {$lookup: {
        from: 'PaymentTypes',
        localField: 'paymentTypeId',
        foreignField: '_id',
        as: 'paymentType'
      }}, {$unwind: {
        path: "$status"
      }}, {$unwind: {
        path: "$paymentType",
      }}]
)

However in C# it never finds any document:

      var orders = await _ordersCollection.Aggregate()
                .Lookup(_statusCollection, order => order.StatusId, status => status.Id, (Order order) => order.Status)
                .Lookup(_paymentTypeCollection, order => order.PaymentTypeId, paymentType => paymentType.Id, (Order order) => order.PaymentType)
                .Unwind(order => order.Status)
                .Unwind(order => order["paymentType"])
                .ToListAsync();

I have the following objects:

    public class Order
    {
        [BsonId(IdGenerator = typeof(GuidGenerator))]
        public Guid Id { get; set; }

        [BsonElement("status")]
        [BsonIgnoreIfNull]
        public Status Status { get; set; }

        [BsonElement("paymentType")]
        [BsonIgnoreIfNull]
        public PaymentType PaymentType { get; set; }

        [BsonElement("paymentTypeId")]
        public Guid PaymentTypeId { get; set; }

        [BsonElement("orderStatusId")]
        public Guid StatusId { get; set; }

    }

    public class PaymentType
    {
        [BsonId(IdGenerator = typeof(GuidGenerator))]
        public Guid Id { get; set; }

        [BsonElement("name")]
        public string Name { get; set; }
    }

    public class Status
    {
        [BsonId(IdGenerator = typeof(GuidGenerator))]
        public Guid Id { get; set; }

        [BsonElement("name")]
        public string Name { get; set; }
    }
  • So, my C# query actually works (I had a problem with the id types). Now I have another issue. The first unwind changes the return type from my expected ICollection to ICollection so I'm forced to run a foreach and deserialize: `var orders = new List(); foreach (var order in ordersResult) { var bla = BsonSerializer.Deserialize(order); orders.Add(bla); }` Any idea how to improve this? – IoanaPatricia Mar 18 '21 at 08:22
  • [Does this](https://stackoverflow.com/a/30450536/1390548) answer your question – Jawad Mar 18 '21 at 13:28

0 Answers0