I'm kind of new with MongoDB driver, so I'm having a bit of confusion regarding queries.
I have collections with the following classes:
[BsonCollection("alerts")]
public class Alert
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public string AlertTypeId { get; set; }
[BsonIgnore]
public AlertType AlertType { get; set; }
}
[BsonCollection("alert_types")]
public class AlertType
{
public ObjectId Id { get; set; }
public string Name { get; set; }
}
I'm trying to populate the property AlertType in Alert, using Lookup operator. I tried the following:
var collection = database.GetCollection<Alert>(GetCollectionName(typeof(Alert)));
var query = collection.Aggregate()
.Lookup("alert_types", "AlertTypeId", "Id", "AlertType")
.Unwind("AlertType")
.As<Alert>()
.ToList();
But this returns an empty List.
I also tried it this way:
var query = collection.Aggregate()
.Lookup("alert_types", x => ObjectId.Parse(x.AlertTypeId), y => y.Id, "AlertType")
.Unwind("AlertType")
.As<Alert>()
.ToList();
But I get the error in Lookup markup:
"The type arguments for method 'IAggregateFluent.Lookup<TForeignDocument, TNewResult>(string, FieldDefinition, FieldDefinition, FieldDefinition, AggregateLookupOptions<TForeignDocument, TNewResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly."
Moreover, tried with collections as Queryable in this way:
IEnumerable<Alert> query = from a in collection.AsQueryable()
join o in typesCollection.AsQueryable() on a.AlertTypeId equals o.Id.ToString() into joinedAlertTypes
select new Alert(a, joinedAlertTypes.FirstOrDefault());
(Implementing, as you can see, a constructor in Alert which assigns all its properties and also the AlertType from the join)
But I get error:
Unable to determine the serialization information for the inner key selector in the tree: aggregate([]).GroupJoin(aggregate([]), a => a.AlertTypeId, o => o.Id.ToString(), (a, joinedAlertTypes) => new <>f__AnonymousType0`2(a = a, joinedAlertTypes = joinedAlertTypes))
What am I doing wrong?
The type arguments for method... cannot be inferred from the usage
you should specify the generic arguments explicitly.