Skip to content

Instantly share code, notes, and snippets.

@selloutdesign
Created August 25, 2017 20:48
Show Gist options
  • Save selloutdesign/e9d879de17b1a5e39358bf912ce04bbe to your computer and use it in GitHub Desktop.
Save selloutdesign/e9d879de17b1a5e39358bf912ce04bbe to your computer and use it in GitHub Desktop.
Mongodb
show dbs #shows all databases
use db_name #use database with given name(creates if does not exist)
Basic Queries
db.user.insert({name: {first: 'Rajesh', last: 'Thummalapally'}, skills: ["Ruby on Rails", "jQuery", "CSS", "HTML5", "C#"]})
db.user.insert({name: {first: 'Teja', last: 'Thummalapally'}, skills: ["Ruby on Rails", "jQuery", "CSS", "HTML5", "Java", "Cooking"]})
db.user.find() #returns collection
db.user.findOne() #returns first one from collection
TO update a user:
db.user.update({query},{updated_full_data},{upsert: true})
ex: db.user.update({'name.first': 'Teja'},{"name" : { "first" : "Teja", "last" : "Thummalapally" }, "skills" : [ "Ruby on Rails", "jQuery", "CSS", "HTML5", "Java", "Cooking" ], "address": {"city": "Gaithersburg"}},{upsert: 'true'})
db.user.find({'address.city': 'Gaithersburg'}) # dot notation
db.user.find({'address': {'city': 'Gaithersburg'}})
Note: Both the notations not always return same results. Dot notation is lenient(refer http://docs.mongodb.org/manual/applications/read/#find)
Using OR in query:
db.user.find({$or: [{'name.first': 'Rajesh'},{'skills': 'Java'}]})
db.user.find({'name.first': /^T/}) #match using regex
db.user.find({'name.first': /^T/},{skills: {$slice: 2}}) #returns only 2 skills
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment