简体   繁体   中英

MongoDB aggregate query count

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

.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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM