Skip to content

Instantly share code, notes, and snippets.

@gserrano
Last active November 25, 2015 00:08
Show Gist options
  • Save gserrano/bf8d19b53ae5fd314697 to your computer and use it in GitHub Desktop.
Save gserrano/bf8d19b53ae5fd314697 to your computer and use it in GitHub Desktop.
Mongo DB basics
// Insert using [].foreEach()
var pokemons = [{
"name": "Pikachu",
"description": "Rato elétrico bem fofinho",
"type": "electric",
"attack": 100,
"height": 0.4
},
{
"name": "Bulbassauro",
"description": "Chicote de trepadeira",
"type": "grama",
"attack": 49,
"height": 0.4
},
{
"name": "Charmander",
"description": "Esse é o cão chupando manga de fofinho",
"type": "fogo",
"attack": 52,
"height": 0.6
},
{
"name": "Squirtle",
"description": "Ejeta água que passarinho não bebe",
"type": "água",
"attack": 48,
"height": 0.5
},
{
"name": "Caterpie",
"description": "Larva lutadora",
"type": "inseto",
"attack": 30,
"height": 0.3
}]
pokemons.forEach(function(pokemon,index,array){db.pokemons.save(pokemon)});
// Edit and save using findOne
var query = {name: "Caterpie"};
var pokemon = db.pokemons.findOne(query);
pokemon.xp = 0;
db.pokemons.save(pokemon);
// $lt, $lte, $gt, $gte
var query = {height : {$lte: 0.3} };
db.pokemons.find(query);
// $or, $nor, $and
var query = {$or : [ {name : 'Caterpie'}, {height : {$lte : 0.4}} ] };
db.pokemons.findOne(query);
// $exists
db.pokemons.find({ xp : {$exists : true} });
//$set
//Update or create fields in document
var query = {"_id": ObjectId("564e7a88d7293fd0242be923")};
var mod = {$set: {
"name": "Caterpie",
"description": "Larva lutadora",
"type": "inseto",
"attack": 30,
"height": 0.3
}};
db.pokemons.update(query, mod);
//$unset
//Remove field from document
var mod = {$unset : {xp : 1}};
db.pokemons.update(query, mod);
db.pokemons.find(query);
// $inc
// Increment value in field
var mod = {$inc : {xp : 15}}
db.pokemons.update(query, modification);
var mod = {$inc : {xp : -100}}
db.pokemons.update(query, modification);
// $push / $pullvar mod = {$set: {
"name": "Caterpie",
"description": "Larva lutadora",
"type": "inseto",
"attack": 30,
"height": 0.3
}}
// push to array field (or create array)
var query = {name : /pikachu/i};
var mod = {$push : {moves : 'Choque do Trovão'}};
db.pokemons.update(query, mod);
// $pushAll / $pullAll
var mod = {$pushAll : {moves : attacks}};
var attacks = ['Choque do Trovão', 'Ataque Rápido', 'Patada'];
var mod = {$pushAll : {moves : attacks}};
db.pokemons.update(query, mod);
// Upsert + options
// $setOnInsert -> used when upsert create a new document
var query = {name: /NaoExiste/i}
var mod = {
$set: {
active: true
},
$setOnInsert:{
name: 'Desconhecido',
attack: null,
defense: null,
height: null,
description : 'Desconhecido'
}
}
var options = {
upsert: true
}
db.pokemons.update(query, mod, options)
// $in
// return documents where field array contain ANY of the array values
var query = {moves: { $in : [/hidrobomba/i]}}
db.pokemons.find(query);
// $nin
// return documents where field array DO NOT contain ANY of the array values
var query = {moves: { $nin : [/hidrobomba/i]}}
db.pokemons.find(query);
// $all
// return documents where field array contain ALL the array values
var query = {moves: {$all: [/hidrobomba/i, /investida/i]}}
// $ne (not equal)
var query = {type : {$ne: grama}}
db.pokemons.find(query)
// $not
var query = { name: {$not : /pikachu/i} }
db.pokemons.find(query);
// remove
var query = {name : /desconhecido/i}
db.pokemons.remove()
//count
var query = { name: {$not : /pikachu/i} }
db.pokemons.count(query)
// distinct
db.pokemons.distinct('type')
// limit, skip
db.pokemons.find({}, { name: 1, _id:0}).limit(2).skip(2 * 0);
db.pokemons.find({}, { name: 1, _id:0}).limit(2).skip(2 * 1);
db.pokemons.find({}, { name: 1, _id:0}).limit(2).skip(2 * 2);
// group
db.pokemons.group({
initial: {total : 0},
reduce: function(curr, result){
curr.moves.forEach(function(move){
if(result[move]){
result[move]++;
}else{
result[move] = 1;
}
result.total++;
})
}
})
// group / cond (conditional query)
db.pokemons.group({
initial: {total : 0},
cond: { attack : {$gt : 50}},
reduce: function(curr, result){
curr.moves.forEach(function(move){
if(result[move]){
result[move]++;
}else{
result[move] = 1;
}
result.total++;
})
}
})
// group finalize
// calculate average attack
db.pokemons.group({
initial: {total:0, attack : 0},
//cond: { attack : {$gt : 50}},
reduce: function(current, result){
result.total++;
result.attack += current.attack;
},
finalize: function(result){
result.attack_avg = result.attack / result.total;
}
})
//Agreggate
db.pokemons.aggregate({
$group: {
_id: {},
attack_avg: {$avg : '$attack' },
attack: {$sum: '$attack'},
total: {$sum: 1}
}
})
//Agreggate using match (find query)
db.pokemons.aggregate([
{
$match : { attack : {$gt : 50}}
},
{
$group: {
_id: {},
attack_avg: {$avg : '$attack' },
attack: {$sum: '$attack'},
total: {$sum: 1}
}
}
])
//.aggregate $unwind (agrupamento com count por "coluna")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment