Skip to content

Instantly share code, notes, and snippets.

@antoniojps
Last active December 9, 2020 10:37
Show Gist options
  • Save antoniojps/c7ca127d00a8a237de8e5da9ea83d882 to your computer and use it in GitHub Desktop.
Save antoniojps/c7ca127d00a8a237de8e5da9ea83d882 to your computer and use it in GitHub Desktop.

start mongo db

$ cd ~/mongo/bin
$ ./mongod --dbpath ~/mongo-data (or w.e path)
or
$ cd ~/mongo/bin && ./mongod --dbpath ~/mongo-data (or w.e path)
or
$ brew services start [email protected]

stop mongo db

brew services stop [email protected]

mongo cli

$ cd ~/mongo/bin
$ ./mongo

create or use db

> use db-name

check db you are in

> db

create user in db

> db.createUser({"user":"antonio","pwd":"123","roles":["readWrite","dbAdmin"]});

create collection

> db.createCollection('name')

insert document or multiple (typeof document Array or Object)

> db.collection.insert({document})

$set

update without having to write whole document collection = costumers

> db.costumers.update({firstname:'Antonio'},{$set:{gender:'Male'}})

inc

increment number (must be number and not string) will increment age by 1 ++

>  db.costumers.update({firstname: 'Antonio'},{$inc:{age:1}})

unset

remove field/prop from document

>  db.costumers.update({firstname: 'Antonio'},{$unset:{age:''}})

upsert

update or insert if doesnt exist

> db.costumers.update({firstname: 'Raimundo'},{$set:{lastname:'Oliveira',age:34}},{upsert:true})

rename

rename field/prop on matched documents

> db.costumers.update({firstname: 'Jasmim'},{$rename:{"gender":"sex"}})

remove

remove all matched

> db.costumers.remove({firstname: 'Raimundo'})

remove just one

>  db.costumers.remove({firstname:"Raimundo"},{justOne:true})

find

all

> db.costumers.find()

match specific field

>  db.costumers.find({firstname:'Jasmim'})

$or

match different fields

>  db.costumers.find({$or:[{firstname:'Jasmim'},{firstname:'Antonio'}]})

$lt, $gt, $lte, $gte

lower then ($lt) and greater then ($gt) lower then or equal to ($lte) greater then or equal to ($gte)

>  db.costumers.find({age:{$lt:40}})
>  db.costumers.find({age:{$gt:40}})

sort

1 for ascending -1 for descending

>  db.costumers.find().sort({age:1}); 

$exists

find all that have/dont have specific field

>  db.costumers.find({age:{$exists:true}})

count()

returns number of found items

>  db.costumers.find({name:"Antonio"}).count()

limit(int)

limit number of documents returned by query

>  db.costumers.find().limit(4)

forEach(function(doc){})

print('txt')

run function for reach doc found

>  db.costumers.find().forEach(function(doc){print('The name is '+doc.firstname)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment