-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathAggregationExamples.cs
269 lines (241 loc) · 8.88 KB
/
AggregationExamples.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
using System;
using System.Collections.Generic;
using System.Linq;
using Task = System.Threading.Tasks.Task;
using Examples;
using MongoDB.Bson;
using NUnit.Framework;
using Realms;
using Realms.Sync;
using Examples.Models;
namespace Examples
{
public class AggregationExamples
{
App app;
Realms.Sync.User user;
PartitionSyncConfiguration config;
const string myRealmAppId = Config.appid;
MongoClient mongoClient;
MongoClient.Database dbPlantInventory;
MongoClient.Collection<Plant> plantsCollection;
Plant venus;
Plant sweetBasil;
Plant thaiBasil;
Plant helianthus;
Plant petunia;
[OneTimeSetUp]
public async Task Setup()
{
app = App.Create(myRealmAppId);
user = app.LogInAsync(Credentials.EmailPassword("foo@foo.com", "foobar")).Result;
config = new PartitionSyncConfiguration("myPart", user);
//:remove-start:
config.Schema = new[] { typeof(Plant) };
//:remove-end:
SetupPlantCollection();
await plantsCollection.DeleteManyAsync();
venus = new Plant
{
Name = "Venus Flytrap",
Sunlight = Sunlight.Full.ToString(),
Color = PlantColor.White.ToString(),
Type = PlantType.Perennial.ToString(),
Partition = "Store 42"
};
sweetBasil = new Plant
{
Name = "Sweet Basil",
Sunlight = Sunlight.Partial.ToString(),
Color = PlantColor.Green.ToString(),
Type = PlantType.Annual.ToString(),
Partition = "Store 42"
};
thaiBasil = new Plant
{
Name = "Thai Basil",
Sunlight = Sunlight.Partial.ToString(),
Color = PlantColor.Green.ToString(),
Type = PlantType.Perennial.ToString(),
Partition = "Store 42"
};
helianthus = new Plant
{
Name = "Helianthus",
Sunlight = Sunlight.Full.ToString(),
Color = PlantColor.Yellow.ToString(),
Type = PlantType.Annual.ToString(),
Partition = "Store 42"
};
petunia = new Plant
{
Name = "Petunia",
Sunlight = Sunlight.Full.ToString(),
Color = PlantColor.Purple.ToString(),
Type = PlantType.Annual.ToString(),
Partition = "Store 47"
};
var listofPlants = new List<Plant>
{
venus,
sweetBasil,
thaiBasil,
helianthus,
petunia
};
var insertResult = await plantsCollection.InsertManyAsync(listofPlants);
return;
}
private void SetupPlantCollection()
{
mongoClient = user.GetMongoClient("mongodb-atlas");
dbPlantInventory = mongoClient.GetDatabase("inventory");
plantsCollection = dbPlantInventory.GetCollection<Plant>("plants");
}
[Test]
public async Task GroupsAndCounts()
{
if (plantsCollection == null)
{
SetupPlantCollection();
}
// :snippet-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}");
}
// :snippet-end:
Assert.AreEqual(PlantType.Annual.ToString(), aggResult[0]["_id"] != null ? aggResult[0]["_id"].AsString : "null");
Assert.AreEqual(PlantType.Perennial.ToString(), aggResult[1]["_id"].AsString);
Assert.AreEqual(3, aggResult[0]["count"].AsInt32);
Assert.AreEqual(2, aggResult[1]["count"].AsInt32);
// :snippet-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}");
}
// :snippet-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);
}
[Test]
public async Task Filters()
{
if (plantsCollection == null)
{
SetupPlantCollection();
}
// :snippet-start: agg_filter
var matchStage = new BsonDocument("$match",
new BsonDocument("type",
new BsonDocument("$eq",
PlantType.Perennial)));
// Alternate approach using BsonDocument.Parse(...)
matchStage = BsonDocument.Parse(@"{
$match: {
type: { $eq: '" + PlantType.Perennial + @"' }
}}");
var sortStage = BsonDocument.Parse("{$sort: { _id: 1}}");
var aggResult = await plantsCollection.AggregateAsync<Plant>(matchStage, sortStage);
foreach (var plant in aggResult)
{
Console.WriteLine($"Plant Name: {plant.Name}, Color: {plant.Color}");
}
// :snippet-end:
Assert.AreEqual(venus.Id, aggResult[0].Id);
Assert.AreEqual(venus.Name, aggResult[0].Name);
Assert.AreEqual(thaiBasil.Id, aggResult[1].Id);
Assert.AreEqual(thaiBasil.Partition, aggResult[1].Partition);
}
[Test]
public async Task Projects()
{
if (plantsCollection == null)
{
SetupPlantCollection();
}
// :snippet-start: agg_project
var projectStage = new BsonDocument("$project",
new BsonDocument
{
{ "_id", 0 },
{ "_partition", 1 },
{ "type", 1 },
{ "name", 1 },
{ "storeNumber",
new BsonDocument("$arrayElemAt",
new BsonArray {
new BsonDocument("$split",
new BsonArray
{
"$_partition",
" "
}), 1 }) }
});
var sortStage = BsonDocument.Parse("{$sort: { storeNumber: 1}}");
var aggResult = await plantsCollection.AggregateAsync(projectStage, sortStage);
foreach (var item in aggResult)
{
Console.WriteLine($"{item["name"]} is in store #{item["storeNumber"]}.");
}
// :snippet-end:
// :snippet-start: agg_project_alt
projectStage = BsonDocument.Parse(@"
{
_id:0,
_partition: 1,
type: 1,
name: 1,
storeNumber: {
$arrayElemAt: [
{ $split:[
'$_partition', ' '
]
}, 1 ]
}
}");
// :snippet-end:
Assert.AreEqual(5, aggResult.Length);
//Assert.Throws<KeyNotFoundException>(() => aggResult[0].GetElement("_id"));
Assert.AreEqual("storeNumber=42", aggResult[0].GetElement("storeNumber").ToString());
}
[OneTimeTearDown]
public async Task TearDown()
{
if (plantsCollection == null)
{
SetupPlantCollection();
}
await plantsCollection.DeleteManyAsync();
return;
}
}
}