Last active
March 13, 2024 04:27
-
-
Save sindbach/6eb227cd2ca81c3d752f 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 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