Skip to content

Instantly share code, notes, and snippets.

@leohmoraes
Last active September 21, 2019 00:50
Show Gist options
  • Save leohmoraes/3ea3c440c158969ea3cdbd2921b639b3 to your computer and use it in GitHub Desktop.
Save leohmoraes/3ea3c440c158969ea3cdbd2921b639b3 to your computer and use it in GitHub Desktop.
Mongo

Criar um container com o mongo

  • docker run --name NOME_BASE -p 27017:27017 -d -t mongo

  • Criar a base NOME_BASE

CONECTAR NO SSH

  • mongo mongodb://localhost:27017/NOME_BASE

Criando um indice

	ensureIndex( { id:1}, { unique:true, dropDups:true } )

Removendo duplicados

db.tickets
  .find({id:1})
  .sort({_id:1})
  .forEach(function(doc){
    db.tickets
      .remove({ _id: {$gt:doc._id}, id:doc.id });
    })

Corrigindo valores

R$ 9,99 -> 9.99 Usando o shell

db
use NOME_BASE
db.tickets.find({ inicio : /12\/09/  }).forEach(function(obj) { 
    obj.price = obj.valor.replace(/R\$ /g, ''); 
    obj.price = obj.price.replace(/,/, '.');   
    obj.price = NumberDecimal(obj.price);
    db.tickets.save(obj);
});

Soma de Valores usando o MongoDB Compass:

{
 _id: { day: { $dayOfYear: ISODate("$inicio")} },
 total: { $sum: "$price" },
 count: { $sum: 1 }
}
ok abaixo
db.tickets.aggregate([
    { "$match": { "inicio": /14\/09/}},
    { "$group": { "_id": null, "total": { "$sum": "$price" }}}
]);

Rodando no Shell

db.tickets.aggregate(
   [
     {
       $group:
         {
           _id: { day: { $dayOfYear: ISODate("$inicio")} },
           total: { $sum: "$price" },
           count: { $sum: 1 }
         }
     }
   ]
);

Ideia

db.tickets.aggregate(
   [
     {
       $group:
         {
           _id: { day: { $dayOfYear: "$inicio"}, year: { $year: "$inicio" } },
           total: { $sum: "$price" },
           count: { $sum: 1 }
         }
     }
   ]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment