Skip to content

Instantly share code, notes, and snippets.

@johndpope-karhoo
Forked from thoragio/mongo-notes.js
Created October 26, 2016 17:31
Show Gist options
  • Select an option

  • Save johndpope-karhoo/2dba5bf3f348c2b95312671d0835945f to your computer and use it in GitHub Desktop.

Select an option

Save johndpope-karhoo/2dba5bf3f348c2b95312671d0835945f to your computer and use it in GitHub Desktop.
Mongo Notes
db.COLLECTION-NAME.findOne()
db.COLLECTION-NAME.find({"key":"value"})
db.COLLECTION-NAME.find().count()
db.COLLECTION-NAME.find().pretty()
db.COLLECTION-NAME.remove({})
db.COLLECTION-NAME.drop()
use DB-NAME (select a DB to use, even if it does not exist)
var c = db.COLLECTION-NAME.find({"key":"value"})
c.hasNext()
c.next()
db.COLLECTION-NAME.insertOne()
db.COLLECTION-NAME.insertMany()
db.COLLECTION-NAME.insertMany([{}], {ordered:false})
db.movieDetails.find({writers: ["Joel Cohen", "Ethan Cohen"]}) // order matters, will only find documents with Joel & Ethan (no other writers) && in that order, this happens because search values are enclosed in an array
db.movieDetails.find({"actor.0":"Jeff Bridges"}) // finds records with JB as the first actor in the list
db.movieDetails.find({"actor":"Jack Black"},{"title":1}) // projection to limit data sent back for query results (in this case, only the title is returned)
db.movieDetails.find({"actor":"Jack Black"},{"title":1, "_id":0}) // and leave out the _id
db.movieDetails.find({"tomato.meter":{$gte:99}, "runtime":{$gte:120}}) // using comparison operators
db.movieDetails.find({"rated":{$ne:"UNRATED"}}) // $ne is not equal to and also includes all documents WITHOUT the searched field
db.movieDetails.find({"rated":{$in:["G", "PG"]}}).count() // $in to find matches from an array of options
db.movieDetails.find( { $and: [ { "genres": { $all: ["Comedy", "Crime"] } }, {"genres": { $size: 2} } ] } )
db.movieDetails.find( { $and: [ { "genres.0": "Comedy" }, { "genres.1": "Crime" }, { "genres": { $size: 2 } } ] } )
db.movieDetails.updateOne({title: "The Martian"}, { $set: { "awards" : {"wins" : 10 } } } )
db.movieDetails.updateMany({"imdb.votes":{$lt:10000}, $and: [ {"year":{$gte:2010}}, {"year":{$lte:2013}}], "tomato.consensus":null}, {$unset: {"tomato.consensus":""}})
db.students.ensureIndex({'teachers':1})
db.students.find({teachers:{$all:[0,1]}}).explain()
db.students.createIndex({student_id:1})
// user true flag to get more details on the query, like number of documents examined
db.students.explain(true).find({student_id:5})
//compound
db.students.createIndex({student_id:1, class_id:-1})
db.students.getIndexes()
db.students.dropIndex({student_id:1, class_id:-1})
// create index with a key and sub-key (dot notation)
db.people.createIndex({"work_history.company":-1})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment