Skip to content

Instantly share code, notes, and snippets.

@NimaAra
Last active June 26, 2019 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NimaAra/a8b46d83df75086104448e9ce31fca81 to your computer and use it in GitHub Desktop.
Save NimaAra/a8b46d83df75086104448e9ce31fca81 to your computer and use it in GitHub Desktop.
MongoDB Quickies
private void Flatten(JToken token, IDictionary<string, JValue> output, string prefix = "")
{
if (token is JObject jObj)
{
foreach(var item in token)
{
Flatten(item, output, prefix);
}
} else if (token is JArray jArr)
{
for (var i = 0; i < jArr.Count; i++)
{
var item = jArr[i];
Flatten(item, output, prefix + "." + "$" + i.ToString());
}
} else if (token is JProperty jProp)
{
if (prefix.Length > 0) { prefix = prefix + "."; }
if (jProp.Value is JValue jValue) {
output[prefix + jProp.Name] = jValue;
} else {
Flatten(jProp.Value, output, prefix + jProp.Name);
}
}
}
db.purchase_orders.aggregate(
[{
$match: {
customer: {
$in: ["Mike", "Karen"]
}
}
}, {
$group: {
_id: "$customer",
total: {
$sum: "$total"
}
}
}, {
$sort: {
total: -1
}
}
], {
"explain": false,
"allowDiskUse": true,
"cursor": {
'batchSize': 5
}
});
db.purchase_orders.aggregate(
[{
$match: {}
}, {
$group: {
_id: "$customer",
total: {
$sum: "$total"
}
}
}, {
$sort: {
total: -1
}
}
]);
db.purchase_orders.aggregate(
[{
"$group": {
"_id": "$customer",
"count": {
"$sum": 1
}
}
}, {
"$match": {
"count": {
"$gte": 5
}
}
}, {
"$sort": {
"count": -1
}
}
]);
public static class Parser
{
public static BsonValue ToBsonValue(this JToken token) => ParseRecursively(token);
private static BsonValue ParseRecursively(JToken token)
{
switch (token)
{
case JObject jObj:
var doc = new BsonDocument();
foreach (var (key, value) in jObj)
{
doc[key] = ParseRecursively(value);
}
return doc;
case JArray jArr:
var arr = new BsonArray();
foreach (var item in jArr)
{
arr.Add(ParseRecursively(item));
}
return arr;
case JValue jVal:
return BsonValue.Create(jVal.Value);
default:
throw new NotImplementedException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment