Forked from sindbach/polymorphic_aggregation_model.cs
Created
February 6, 2023 13:05
-
-
Save aeleftheriadis/ec6102e0c905e7763c75cdb7b82d5f53 to your computer and use it in GitHub Desktop.
A simple C# example to demonstrate polymorphic abstract classes to interact with MongoDB aggregation result.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using MongoDB.Bson; | |
using MongoDB.Driver; | |
using MongoDB.Bson.Serialization.Attributes; | |
public abstract class MongoModelBase | |
{ | |
[BsonId] | |
public ObjectId Id { get; set; } | |
} | |
[BsonDiscriminator(Required = true, RootClass = true)] | |
[BsonKnownTypes(typeof(OrganizationActivityLog), typeof(ShipmentActivityLog))] | |
public abstract class ActivityLogBase : MongoModelBase | |
{ | |
public string ActivityDescription { get; set; } | |
} | |
public class ShipmentActivityLog : ActivityLogBase | |
{ | |
public string shipmentId { get; set; } | |
} | |
public class OrganizationActivityLog : ActivityLogBase | |
{ | |
public int OrganizationId { get; set; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var client = new MongoClient("mongodb://localhost:27017"); | |
var database = client.GetDatabase("test"); | |
var collection = database.GetCollection<ActivityLogBase>("activitylogs"); | |
var filterBuilder = Builders<OrganizationActivityLog>.Filter; | |
var result = collection.Aggregate() | |
.OfType<OrganizationActivityLog>() | |
.Group( | |
e => e.OrganizationId, | |
e => new { | |
ActivityLog = e.Select(f => new OrganizationActivityLog | |
{ | |
Id = f.Id, | |
OrganizationId = f.OrganizationId, | |
ActivityDescription = f.ActivityDescription | |
}).First() | |
} | |
).ToList(); | |
Console.WriteLine(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment