Jeff Codes
Jeff Codes

Reputation: 77

MongoDB C# 2.4 - Find distinct values of nested array

I have documents that look like below:

{
    "_id" : ObjectId("58148f4337b1fc09b8c2de9k"),
    "Price" : 69.99,
    "Attributes" : [ 
        {
            "Name" : "Color",
            "Value" : "Grey",
        },
        {
            "Name" : "Gender",
            "Value" : "Mens",
        }
    ]
}

I am looking to get a distinct list of Attributes.Name (so if I just had the one document as above, I would get 'Color' and 'Gender' returned).

I was able to easily get what I needed through mongo shell (db.getCollection('myCollection').distinct('Attributes.Name'), but I'm really struggling with the C# driver (version 2.4). Can someone please help me translate the shell command to C#?

I tried something like below (and many variations). I'm new to the Mongo C# driver and am just feeling a bit lost. Any help would be appreciated.

var database = client.GetDatabase("mymongodb");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("mycollection");
var filter = new BsonDocument();
var distinctAttributeNames = collection.Distinct<BsonDocument>("Attributes.Name", filter);
var tryAgain = collection.Distinct<BsonDocument>("{Attributes.Name}", filter);

Upvotes: 1

Views: 3398

Answers (1)

dnickless
dnickless

Reputation: 10918

There you go:

public class Foo
{
    public ObjectId Id;
    public double Price = 69.99;
    public Attribute[] Attributes = {
        new Attribute { Name = "Color", Value = "Grey" },
        new Attribute { Name = "Gender", Value = "Men" }
    };
}

public class Attribute
{
    public string Name;
    public string Value;
}

public class Program
{
    static void Main(string[] args)
    {
        MongoClient client = new MongoClient();
        var collection = client.GetDatabase("test").GetCollection<Foo>("test");
        collection.InsertOne(new Foo());
        var distinctItems = collection.Distinct(new StringFieldDefinition<Foo, string>("Attributes.Name"), FilterDefinition<Foo>.Empty).ToList();
        foreach (var distinctItem in distinctItems)
        {
            Console.WriteLine(distinctItem);
            // prints:
            // Color
            // Gender
        }
        Console.ReadLine();
    }
}

Upvotes: 5

Related Questions