giovictor
7/31/2019 - 9:01 AM

MongoDB Queries

Mongo DB queries to run on the actual database itself

Mongo DB Queries

READ: All text that are uppercase are just placeholders and can be replaced

show dbs - show databases that have collections

use DBNAME - switch to use database or create a new database

show collections - show collections of the currently used database

db - to show currently used database

db.dropDatabase() - delete currently used database

db.createCollection('COLLECTION') - create collection

db.COLLECTION.insert(DATA) - insert data in collection (data must be an object)

db.COLLECTION.insertMany(DATAS) - insert many datas in collection (datas must be objects)

db.COLLECTION.find() - show all datas in collection (add a .pretty() method for a formatted result)

db.COLLECTION.findOne(CONDITION) - show only one data in collection (add a .pretty() method for a formatted result)

db.COLLECTION.find().sort({FIELD:1}) show all datas in collection based on a field in ascending or descending (1 for ASC, -1 for DESC)

db.COLLECTION.find(CONDITION) - show all datas in collection based on a condition (like WHERE clause in SQL) condition must be an object

db.COLLECTION.find().count() - show counts of data in collection (can also be based on a condition)

db.COLLECTION.find().limit(LIMIT) - show limited data in collection (can also be based on a condition) based on the number passed in limit()

db.COLLECTION.update(CONDITION, UPDATED_DATA) - update all entries of a collection based on a condition (add {upsert:true} in update() if you wanted the new data to be inserted in the collection if a condition did not match any data)

db.COLLECTION.update(CONDITION, { $set:{UPDATED_DATA} }) - update some entries of a collection based on a condition (add {upsert:true} in update() if you wanted the new data to be inserted in the collection if a condition did not match any data) can also use $inc to increment a data and $rename to rename a field

db.COLLECTION.remove(CONDITION) - remove a data from a collection

db.COLLECTION.createIndex(INDEX) - create a search index

Some other operators: ** $gt and $gte ** - greater than and greater than or equal ** $lt and $lte ** - less than and less than or equal ** $search ** - search query ** $elemMatch ** - matching in multiple datas