Konstantin
Konstantin

Reputation: 1280

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

Upvotes: 3

Views: 5436

Answers (3)

Maybe you can use aggregate functions:

Example, my collection:

enter image description here

The code:

 var dist = dbCollection.Aggregate().Group(d => d.Name, o =>
            new
            {   
                Name = o.Key,
                Data = o.Select(_ => _.Symbol).Distinct(),
            }).ToEnumerable();

            dist.ToList().ForEach(_ =>
                {
                    _.Data.ToList().ForEach(d => Console.WriteLine("Company: " +_.Name + " Symbol: " + d));
                }
            );

Result:

enter image description here

Upvotes: 5

Senthur Deva
Senthur Deva

Reputation: 787

This is working fine $group $project

    db.col.aggregate([{
        "$group": {
            "_id": {
                "symbol": "$symbol",
                "companyName": "$companyName"
            },
            "occurrences": {
                "$sum": 1
            }
        }
    },
    {
        "$project": {
            "symbol": "$_id.symbol",
            "companyName": "$_id.companyName",
            "occurrences": "$occurrences",
            "_id": 0
        }
    }
])

Upvotes: 2

Konstantin
Konstantin

Reputation: 1280

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

Upvotes: 2

Related Questions