Пример #1
0
        public async Task GroupsAndCounts()
        {
            // :code-block-start: agg_group
            var groupStage =
                new BsonDocument("$group",
                                 new BsonDocument
            {
                { "_id", "$type" },
                { "count", new BsonDocument("$sum", 1) }
            });

            var sortStage = new BsonDocument("$sort",
                                             new BsonDocument("_id", 1));

            var aggResult = await plantsCollection.AggregateAsync(groupStage, sortStage);

            foreach (var item in aggResult)
            {
                var id    = item["_id"];
                var count = item["count"];
                Console.WriteLine($"Plant type: {id}; count: {count}");
            }

            // :code-block-end:
            Assert.AreEqual(PlantType.Annual.ToString(), aggResult[0]["_id"].AsString);
            Assert.AreEqual(PlantType.Perennial.ToString(), aggResult[1]["_id"].AsString);
            Assert.AreEqual(3, aggResult[0]["count"].AsInt32);
            Assert.AreEqual(2, aggResult[1]["count"].AsInt32);

            // :code-block-start: agg_group_alt
            var groupStep = BsonDocument.Parse(@"
              {
                $group: {
                  _id: '$type', 
                  count: {
                    $sum: 1
                  }
                }
              }
            ");

            var sortStep = BsonDocument.Parse("{$sort: { _id: 1}}");

            aggResult = await plantsCollection.AggregateAsync(groupStep, sortStep);

            foreach (var item in aggResult)
            {
                var id    = item["_id"];
                var count = item["count"];
                Console.WriteLine($"Id: {id}, Count: {count}");
            }
            // :code-block-end:
            Assert.AreEqual(PlantType.Annual.ToString(), aggResult[0]["_id"].AsString);
            Assert.AreEqual(PlantType.Perennial.ToString(), aggResult[1]["_id"].AsString);
            Assert.AreEqual(3, aggResult[0]["count"].AsInt32);
            Assert.AreEqual(2, aggResult[1]["count"].AsInt32);
        }