2

I'm making an application with MongoDB and C#. I use the MongoDB C# driver. I have the following collection:

{
    _id: 5099803df3f4948bd2f98391,
    title: Toy Story,
    genres: [ "Animation", "Comedy" ]
},
{
    _id: 5099803df3f4948bd2f98392,
    title: Minions,
    genres: [ "Animation", "Comedy", "Action" ]
}

Now I want to query on the data and get the how many movies there are for each genre. So the result should be:

Animation: 2
Comedy: 2
Action: 1

I'm trying to achieve this with this code.

database.GetCollection<Movie>("Movies")
     .Aggregate()
     .Unwind<Movie>(x => x.Genres)
     .Group(x=>x.Genres, g => new
     {
          Genre= g.Key,
          Count = g.Select(x=>x.Genres).Count()
     }).ToList();

I changed it multiple times without success

1 Answer 1

3

.Group() is used here to build an expression that gets translated to Aggregation's Framework $group pipeline stage. The thing is that MongoDB's syntax is a bit different than the one you have in LINQ so you should think more "MongoDB way" here.

Technically $group will give you a collection of documents with two fields: _id (this is what grouping key gets translated into) and Count. So to fix your query you can introduce simple type like below:

public class GenreStats
{
    [BsonElement("_id")]
    public string Genre { get; set; }
    public int Count { get; set; }
}

and then use that type to deserialize your aggregation result:

database.GetCollection<Movie>("Movies")
    .Aggregate()
    .Unwind<Movie, Movie>(x => x.Genres)
    .Group(x=>x.Genres, g => new
    {
        Count = g.Count()
    }).As<GenreStats>().ToList();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.