Skip to content

Instantly share code, notes, and snippets.

@abdullah353
Created November 1, 2015 16:38
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 abdullah353/7720c3a25c00c49d921d to your computer and use it in GitHub Desktop.
Save abdullah353/7720c3a25c00c49d921d to your computer and use it in GitHub Desktop.
MongoDB Queries
# Not only have we been adding wands, but our users have been adding new ones daily! Let's create a list of all the unique wand makers in our database.
db.wands.aggregate(
{
"$group": {
"_id": "$maker"
}
}
)
# Most of our users only care about the magic damage for their wand. After all, what's the point of doing awesome spells at low levels? Let's find out how many wands we have for each damage.magic score.
db.wands.aggregate([
{
"$group": {
"_id": "$damage.magic",
"wand_count" : {
"$sum": 1
}
}
}
])
# Our site is a popular resource for wand collectors to find wands by makers they don't yet have. One ambitious connoisseur has asked how much it would cost to buy all the wands for each vendor. Let's find out!
db.wands.aggregate({ $group: {"_id": "$maker", "total_cost":{"$sum":"$price"}}})
# They say that knowledge is power. Let's see what sort of interesting information we can find out based on the data we have. We have a slight suspicion that wand makers like to charge more for wands at "monumental levels". Time to prove it!
db.wands.aggregate({ $group: {"_id": "$level_required", "price_average":{$avg: "$price"}}})
# Let's put together a simple buyer's guide with some basic stats about makers to help our users quickly make wand decisions.
db.wands.aggregate(
{
$group:
{
"_id": "$maker",
"total_wands": {$sum: 1},
"max_magic": {$max: "$damage.magic"},
"lowest_price": {$min: "$price"}
}
}
)
#Some wand powers can be harder to find in lower-level wands. We've heard that the power "Air Bolt" is a really fun one to have. Let's find out which makers offer a wand with that power and find the lowest level_required per maker.
db.wands.aggregate(
{ $match: { "powers": "Air Bolt"}},
{ $group: { "_id": "$maker", "lowest_level": {$min: "$level_required"}}}
)
# A user has asked us to find out which makers have wands that are under 50 gems and have a damage.magic average above 40.
db.wands.aggregate([
{$match: {"price": { "$lt": 50}}},
{$group: { "_id": "$maker", "average_magic": {"$avg": "$damage.magic"}}},
{$match: { "average_magic": {$gt: 40}}}
])
#We're always on the lookout for the best wand for its value. Let's find out the top 5 makers that offer the most magic damage for a wand in our level range.
db.wands.aggregate([
{$match: { "level_required": { $lte: 5 } } },
{$project: {"damage.magic":true,"maker": true,"_id":false}},
{$group: { "_id": "$maker", "max_damage": {$max: "$damage.magic"}}},
{ $sort: { "max_damage": -1}},
{ $limit: 4}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment