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; }
}