[CSHARP-2326] Distinct by multiple Keys Created: 12/Jul/18  Updated: 14/Jun/19  Resolved: 06/Feb/19

Status: Closed
Project: C# Driver
Component/s: Read Operations
Affects Version/s: None
Fix Version/s: None

Type: Task Priority: Major - P3
Reporter: Prashant Assignee: Wan Bachtiar
Resolution: Done Votes: 0
Labels: question
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Find distinct records with the help of multiple keys within a collection in C#. Here, multiple keys are present in an string array.

For example:

If we have a collection, 

collection = { [

{firstName: "John", lastName: "Cena", age: 40}

,{firstName: "Prashant", lastName: "Gupta", age: 45}] }

and we have an array:

multiplekeys = {"lastName","age"}

How can we find the distinct records in the collection using multiple keys?



 Comments   
Comment by Wan Bachtiar [ 18/Jan/19 ]

 

How can we find the distinct records in the collection using multiple keys?

Hi Prashant,

You can use MongoDB Aggregation Pipeline to group by multiple fields to find distinct records as below example:

var condition = new BsonDocument{
                                {"_id", new BsonDocument{
                                    {"lastname", "$lastname"}, 
                                    {"age", "$age"}
                                }}, 
                                {"count", new BsonDocument{{"$sum", 1}}},
};
var documents = collection.Aggregate().Group(condition).ToList();     

See also $group pipeline stage for more information.

Please note that CSHARP project is for reporting bugs or feature suggestions for the MongoDB C# driver. For MongoDB .NET/C# usage discussion please post on the mongodb-user group.

Regards,
Wan.

Generated at Wed Feb 07 21:42:14 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.