Database

MongoDB

Command Description
Database
use DATABASE_NAME Create or switch a database
db Show current database name
show dbs List all databases
db.dropDatabase() Delete current database
Collection
db.createCollection(name[, options]) Create a collection
show collections List all collections
db.COLLECTION_NAME.drop() Delete a collection
Document
db.COLLECTION_NAME.insert(document) Insert document. If COLLECTIONNAME non-exsited, create it and then insert document
db.COLLECTION_NAME.find([query][, projection]) Show all documents inserted
db.COLLECTION_NAME.update() Update document
db.COLLECTION_NAME.save() same as above
db.COLLECTION_NAME.find().pretty() Show documents updated
db.COLLECTION_NAME.remove() Remove document

To update a document, you need to know that:

db.COLLECTION_NAME.update(
    <query>,
    <update>,
    {
      upert: <boolean>,
      multi: <boolean>,
      writeConcern: <document>
    }
)

or

bd.COLLECTION_NAME.save(
    <document>,
    {
      writeConcern: <document>
    }
)

Arguments introduction:

  • query - conditions of querying;
  • update -
  • upsert - optional, false (default), ?insert objNEW;
  • multi - optional, false (default), ?query all items;
  • writeConcern - optional, level of error-like.
  • document - document data.

To remove document, you need to know that:

db.COLLECTION_NAME.remove(
    <query>,
    <justOne>
)

or(recommended)

db.COLLECTION_NAME.remove(
    <query>,
    {
      justOne: <boolean>,
      writeConcern: <document>
    }
)

Arguments explanations:

  • query - optional, conditions of removing documents;
  • justOne - optional, false (default). If ture or 1, just remove the first patterned document.
  • writeConcern - optional, level of error-like.
ToTOP