using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System;
using System.Linq;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
var dbc = new MongoDbCTX();
dbc.Samples.InsertOne(new Sample() \{ TID = "1", UID = "1", CTX = "11", STAT = Status.B }
);
dbc.Samples.InsertOne(new Sample() { TID = "1", UID = "2", CTX = "11", STAT = Status.B });
dbc.Samples.InsertOne(new Sample() { TID = "1", UID = "3", CTX = "11", STAT = Status.C });
dbc.Samples.InsertOne(new Sample() { TID = "1", UID = "4", CTX = "22", STAT = Status.B });
dbc.Samples.InsertOne(new Sample() { TID = "1", UID = "5", CTX = "22", STAT = Status.C });
var x = dbc.Samples.Aggregate()
.Match(x=>x.TID == "1")
.Group(
doc => doc.CTX,
group => new
{
C = group.Key,
B = group.Where(x => x.STAT == Status.B).Count(),
C = group.Where(x => x.STAT == Status.C).Count(),
}
).ToList();
}
}
public class MongoDbCTX
{
private readonly IMongoClient _mongoDbClient = null;
private readonly IMongoDatabase _mongoDb = null;
public IMongoCollection<Sample> Samples => _mongoDb.GetCollection<Sample>(nameof(Samples));
public MongoDbCTX()
{
_mongoDbClient = new MongoClient("mongodb://localhost");
_mongoDb = _mongoDbClient.GetDatabase("test");
}
public IAggregateFluent<TDocument> Aggregate<TDocument>() =>
_mongoDb.GetCollection<TDocument>(nameof(TDocument)).Aggregate();
}
public class Sample
{
[BsonId]
public string ID => $"\{TID}
{UID}
{CTX}";
public string UID { get; set; }
public string TID { get; set; }
public string CTX { get; set; }
[BsonRepresentation(BsonType.String)] // if disabled it works
public Status STAT { get; set; } = Status.A;
}
public enum Status
{
A,
B,
C,
}
}