Skip to content

Instantly share code, notes, and snippets.

@jbelmont
Last active March 4, 2019 00:24
Show Gist options
  • Save jbelmont/a1d7760264e86cc735f7119b8566e4e6 to your computer and use it in GitHub Desktop.
Save jbelmont/a1d7760264e86cc735f7119b8566e4e6 to your computer and use it in GitHub Desktop.
A list of commands you can use in mongodb.

Basic Commands

Action Run Command Example
Connect to local host on default port 27017 mongo mongo
Connect to remote host on specified port mongo --host --port mongo --host 192.168.65.23 --port 27020
Connect to a database mongo / mongo 192.168.65.23/api
Show current database db db
Select or switch database use use api
Execute a JavaScript file load() load (program.js)
Display help help help
Display help on DB methods db.help() db.help()
Display help on Collection db.mycol.help() db.mycol.help()

Show Commands

Action Run Command Example
Show all databases show dbs show dbs
Show all collections in current database show collections show collections
Show all users on current database show users show users
Show all roles on current database show roles show roles

CRUD Operations

Action Run Command Example
Insert a new document in a collection db.collection.insert( ) db.heroes.insert({"name": "Batman", "powers": ["Super Rich","Tech Gadgets","Batmobile","Martial Artists","Super Style","Alfred"], "gender": "male" })
Insert multiple documents into a collection db.collection.insertMany([ <document1>, <document2>, ... ]) or db.collection.insert([<document1>, <document2>, ... ]) db.heroes.insertMany( [{"name": "Batman", "powers": ["Super Rich","Tech Gadgets","Batmobile","Martial Artists","Super Style","Alfred"], "gender": "male" }, {"name": "Aquaman", "powers", ["Superhuman Strength", "Telepathic Abilities"], "gender": "male"}])
Show all documents in the collection db.collection.find() db.heroes.find()
Filter documents by field value condition db.collection.find() db.heroes.find({"_id": ObjectId("507f1f77bcf86cd799439011")})
Show only some fields of matching documents db.collection.find(, ) db.heroes.find({"_id": "507f1f77bcf86cd799439011"}, {name: true})
Show the first document that matches the query condition db.collection.findOne(, ) db.heroes.findOne({}, {_id:false})
Update specific fields of a single document that match the query condition db.collection.update(, ) db.heores.update({name: "Aquaman"}, {$set : {name :"Aquaman Crisis"}})
Remove certain fields of a single document the query condition db.collection.update(, ) db.heroes.update({name: "Aquaman"}, {$unset : {gender:""}})
Remove certain fields of all documents that match the query condition db.collection.update(, , {multi:true} ) db.heroes.update({gender : "male"}, {$unset : {name:""}}, {multi:true})
Delete a single document that match the query condition db.collection.remove(, {justOne:true}) db.heroes.remove({gender : "male"}, {justOne:true})
Delete all documents matching a query condition db.collection.remove() db.heroes.remove({gender : "male"})
Delete all documents in a collection db.collection.remove({}) db.heroes.remove({})

Index Methods

Action Run Command Example
Create an index db.collection.createIndex( {indexField:type} ) "type" can be 1 for ascending and -1 for descending db.heroes.createIndex({organization:1})
Create a unique index db.collection.createIndex( {indexField:type}, {unique:true} ) db.heroes.createIndex( {crisisMode:1},{unique:true} )
Create a index on multiple fields (compound index) db.collection.createIndex({indexField1:type1, indexField2:type2, ...}) db.heroes.createIndex({name:1, gender:-1})
Show all indexes in a collection db.collection.getIndexes() db.heroes.getIndexes()
Drop an index db.collection.dropIndex( {indexField:type} ) db.heroes.dropIndex({author:-1})
Show index statistics db.collection.stats() db.heroes.stats()

Cursor Methods

Action Run Command Example
Show number of documents in the collection cursor.count() db.heroes.find().count()
Limit the number of documents to return cursor.limit() db.heroes.find().limit(2)
Return the result set after skipping the first n number of documents cursor.skip() db.heroes.find().skip(2)
Sort the documents in a result set in ascending or descending order of field values cursor.sort( <{field : value}> ) where value = 1 for ascending and -1 for descending db.heroes.find().sort( {name : 1} )
Display formatted (more readable) result cursor.pretty() db.heroes.find({}).pretty()

Comparison Operators

Action Run Command Example
equals to {<field>: { $eq: <value> }} db.heroes.find({name: {$eq: "Aquaman"}})
less than {<field>: { $lt: <value> }} db.heroes.find({year: {$lt: 1981}})
less than or equal to {<field>: { $lte: <value> }} db.heroes.find({year:
greater than {<field>: { $gt: <value> }} db.heroes.find({year: {$gt: 1985}})
greater than or equal to {<field>: { $gte: <value> }} db.heroes.find({year: {$gte: 2008}})
not equal to {<field>: { $ne: <value> }} db.heroes.find({year: {$ne: 2008}})
value in {<field>: { $in: [ <value1>, <value2>, ... }} db.heroes.find({year: {$in: [1985, 1991]}})
value not in {<field>: { $nin: [ <value1>, <value2>, ... }} db.heroes.find({year: {$nin: [1981, 1992]}})

Logical Operators

Action Run Command Example
OR { $or: [<expression1>, <expression2>,...]} db.heroes.find( { $or: [{year: {$lte: 1981}}, {year: {$eq: 1991}}]} )
AND { $and: [<expression1>, <expression2>,...]} db.heroes.find( { $and: [{year: {$eq: 1981}}, {gender: {$eq: "male"}}]} )
NOT { $not: {<expression>}} db.heroes.find( {$not: {year: {$eq: 1981} }})
NOR { $nor: [<expression1>, <expression2>,...]} db.heroes.find( { $nor: [{year: {$lte: 1981}}, {year: {$eq: 1993}}]} )

Element Operators

Action Run Command Example
Match documents that contains that specified field {<field>: {$exists:true}} db.heroes.find({ powers: {$exists: true }})
Match documents whose field value is of the specified BSON data type {<field>: {$type:value}} db.heroes.find({name: {$type: 2 }})

MongoDB Server Status

Action Run Command Example
Returns the number of mongo connections db.serverStatus() db.serverStatus().connections

Query Selectors

Comparison

For comparison of different BSON type values, see the specified BSON comparison order. |

Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$in Matches any of the values specified in an array.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$nin Matches none of the values specified in an array.

Logical

Name Description
$and Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$not Inverts the effect of a query expression and returns documents that do not match the query expression.
$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
$or Joins query clauses with a logical OR returns all documents that match the conditions of either clause.

Element

Name Description
$exists Matches documents that have the specified field.
$type Selects documents if a field is of the specified type.

Evaluation

Name Description
$expr Allows use of aggregation expressions within the query language.
$jsonSchema Validate documents against the given JSON Schema.
$mod Performs a modulo operation on the value of a field and selects documents with a specified result.
$regex Selects documents where values match a specified regular expression.
$text Performs text search.
$where Matches documents that satisfy a JavaScript expression.

Geospatial

Name Description
$geoIntersects Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports $geoIntersects.
$geoWithin Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support $geoWithin.
$near Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere and 2d indexes support $near.
$nearSphere Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere.

Array

Name Description
$all Matches arrays that contain all elements specified in the query.
$elemMatch Selects documents if element in the array field matches all the specified $elemMatch conditions.
$size Selects documents if the array field is a specified size.

Bitwise

Name Description
$bitsAllClear Matches numeric or binary values in which a set of bit positions all have a value of 0.
$bitsAllSet Matches numeric or binary values in which a set of bit positions all have a value of 1.
$bitsAnyClear Matches numeric or binary values in which any bit from a set of bit positions has a value of 0.
$bitsAnySet Matches numeric or binary values in which any bit from a set of bit positions has a value of 1.

Comments

Name Description
$comment Adds a comment to a query predicate.

Projection Operators

Name Description
$ Projects the first element in an array that matches the query condition.
$elemMatch Projects the first element in an array that matches the specified $elemMatch condition.
$meta Projects the document’s score assigned during $text operation.
$slice Limits the number of elements projected from an array. Supports skip and limit slices.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment