Search code examples
c#mongodbmongodb-.net-driverdistinct-values

MongoDB C# how to filter documents by multiple distinct fields?


I have a list of company stock prices in a MongoDB. Each document looks like this:

{
"_id":"5b93f2719c02f096d5cb9608",
"dateString":"2018-09-07",
"close":260.87,
"companyName":"Adobe Systems, Inc.",
"high":263.67,
"low":257.12,
"open":258,
"symbol":"ADBE",
"timestamp":1536296400
}

Of course there's a lot of documents like this in the database. I need to get the list of symbols and company names in a distinct manner, e.g. I want to have this:

List<BsonDocument> {
    { "symbol": "ADBE", "companyName": "Adobe Systems, Inc." },
    { "symbol": "MCO", "companyName": "Moody's Corp" }
    ...
}

I've found a way to get distinct values only for one field, like this:

public List<string> GetCompanySymbolNames() {
    return m_CompanyCollection.Distinct<string>("symbol", new BsonDocument())?.ToList();
}

But is there a way to make distinct filtering by 2 fields? It's a C# mongodb driver

p.s. I've seend this topic count multiple distinct fields by group with Mongo But I couldn't make it work with C# driver


Solution

  • I've resolved it like this:

    public List<SymbolItem> GetCompanySymbolItems() {
        // https://docs.mongodb.com/manual/reference/operator/aggregation/group/
        var result = new List<SymbolItem>();
        m_CompanyCollection.Aggregate()
            .Group(new BsonDocument("_id",
                new BsonDocument {{"symbol", "$symbol"}, {"companyName", "$companyName"}}))
            .ToList()
            .ForEach(bson => {
                var symbolData = bson["_id"];
                result.Add(new SymbolItem {
                    Tag = symbolData["symbol"].AsString,
                    Name = symbolData["companyName"].AsString
                });
            });
    
        return result;
    }
    

    Now I'm getting the results I wanted