Mongodb Operators Cheat Sheet



Introduction

  1. Database Cheat Sheet tries to provide a basic reference for beginner and advanced developers, lower the entry barrier for newcomers, and help veterans refresh the old tricks. MongoDB: Queries Cheat Sheet. Using SQL Operators. Combine rows from two queries. SELECT c1, c2 FROM t1 UNION ALL.
  2. Expression Operators¶ These expression operators are available to construct expressions for use in the aggregation pipeline stages. Operator expressions are similar to functions that take arguments. In general, these expressions take an array of arguments and have the following form:.

If you’re looking to use a MongoDB database with your web application running on NodeJS you might be looking at which npm libraries which will allow you to easily interact with MongoDB. Mongoose and MongoJS are the two top choices for developers in this scenario. In this article we’ll give a quick cheat sheet of the common commands you’ll use with the Mongoose library that will quickly get you up and running. We’ll show basic commands and a very quick briefing on what each command does.

There are diffent cheat sheet of mongoDB on mysoftkey.com you can visit each one of them as follows: mongoDB – Admin Cheat Sheet; mongoDB – User Admin Cheat Sheet; mongoDB – Query Cheat Sheet ( comparison between MySQL and MongoDB ) 2. How to graceful shutdown of mongoNode? You can gracefully shutdown a MongoDB node for maintenance. No Comments on Cheat Sheet For MongoDB Commands This article is a cheat sheet for MongoDB commands. You will find a list of the most essential and handy commands that you will frequently use here.

  • Notes:
    • To demo we will use the example of creating a database for a small grocery store with a grocery products as the records.
    • Most of these functions have several optional parameters including a callback that we are choosing not to show here for the sake of simplicity.

Cheat Sheet

Setup

To get setup with Mongoose you’ll have to have mongoose installed from npm using

npm install mongoose

Then you’ll need it required in your models and any js file where you are using it

Schema

The big difference between MongoJS and Mongoose is that Mongoose pushes you to create documents using a schema. You define a schema then create documents using that schema. With MongoJS on the other hand you’re free to do whatever you’d like. Some people prefer the freedom of MongoJS and some people prefer the structure of Mongoose. Since this is the major differentiating point we’ll start with creating a schema.

To create a schema your js will look something like this

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ProductSchema =new Schema({
name:{
type:String,
required:true
},
brand:{
type:String,
required:false
},
order:{
type: Schema.Types.ObjectId,
ref:'Order'
}
});
// This creates our model from the above schema, using mongoose's model method
var Product = mongoose.model('Product', ProductSchema);
// Export the Article model
module.exports= Product;

In this example we’ve created a simple schema that uses a couple primitive String fields “name” and “brand” but also an “order” field which could join with another Schema. This is like a Join in relational databases.

As you can see we create the schema, then create our model from that schema, then lastly we export that model so that our other javascript files can create documents using that model.

Creating documents based on the model

And

To use the model we need to import mongoose and the model. We have our model in a models folder so our code to do so looks like this

var mongoose = require('mongoose');
var db = require('./models');
mongoose.connect('mongodb://localhost:27017/grocerydb',{ useNewUrlParser:true});

Then we create a document like so

var product ={ name:'Soda', brand:'demoBrand'};
db.Product.create(product)
.then(function(dbProduct){
console.log(dbProduct);
})
.catch(function(err){
console.log(err);
});

Mongodb Like Operator

We showed the .then() and .catch() for demonstration of how to handle success and failures but we will omit them in the future examples so we can solely concentrate on Mongoose commands.

Creating multiple documents `jsdb.Product.insertMany([{ name: ‘Soda’ }, { name: ‘Milk’}]);`

Finding documents

We can find all our documents (Products) with a command like below.

Find a document based on id

db.Product.findOne({ _id:<id>})

Updating

Update a single document

db.Product.updateOne({ name:'Soda'},{ brand:'newBrand'});

Update multiple documents

db.Product.updateMany({ brand:'demoBrand'},{ quantity:500});

Delete Documents

Delete a single document

Delete multiple documents

Mongodb Operators Cheat Sheet
db.Product.deleteMany({ quantity:{ $gte:100}});

Conclusion

In this cheat sheet we gave you the basic CRUD ( Create, Read, Update, Delete ) commands that will be commonly used with Mongoose. Mongoose is a very easy library to get up and running with so get started and try out some commands. You can install Mongoose from npm by running npm install mongoose. We hope this cheat serves as a good introduction or as a reminder of how to use Mongoose within your NodeJS. If you have any feedback on commands we could add please don’t hesitate to reach out to us.

MongoDB is a popular NoSQL database that allows unauthenticated access by default.

Regardless of the user’s authentication database, Mongo always stores user information in admin.

MongoDB stores all user information, including name, password, and the user’s authentication database, in the system.users collection in the admin database.

See centralized-user-data and system-users-collection.

When you create a user and grant that user access to a single database (aka their authentication database) then that information can only be stored in the admin database.

Mongodb Operators Cheat Sheet

So, it’s not really a question of “best practice”; storing user details in admin is MongoDB’s choice, as implemented by their user management commands.

Update in response to this comment:

Ok, so the users are always located in the admin db, but I may also add “duplicates” to the other dbs? Maybe the question should be whether there any advantage in adding users to the other “non admin” dbs?

If you intend to have a single user with access to multiple databases then create a single user with roles in each of those databases rather than creating that user multiple times i.e. once in each of those databases. For example:

Create initial admin user

Sharded Cluster with enforced authentication

Create:

  • a cluster-wide admin user
  • a replica set specific admin user

Mongodb Query Language Cheat Sheet

Cluster-wide Admin

Replica Set Admin (a.k.a shard local)

Enable authentication in the mongos configuration

Connect to all replica set member nodes

Authenticate and check that the admin users exist

Log in

Mongodb Operators Cheat Sheet Download

Rename collections

Mongodb Operators Cheat Sheet Excel

Copy Collection

Mongodb Operators Cheat Sheet

Check replication set status

Backup/Restore

Documents

Admin commands

TLS 1.2 for Mongo Routers

To protect your application’s database connection enable TLS on the mongo routers as follows. Note that your mongo driver configuration needs to trust the CA certificate and enable transport encryption with ssl=true.

Rolling Update/Cluster Patching

Maintenance (startup in reverse order):

Replication Concept

  1. write operations go to the primary node
  2. all changes are recorded into operations log
  3. asynchronous replication to secondary
  4. secondaries copy the primary oplog
  5. secondary can use sync source secondary*
  • automatic failover on primary failure

*settings.chainingAllowed (true by default)

Replica set oplog

  • special capped collection that keeps a rolling record of all operations that modify the data stored in the databases
  • idempotent
  • default oplog size (for Unix and Windows systems):

    Storage EngineDefault Oplog SizeLower BoundUpper Bound
    In-memory5% of physical memory50MB50GB
    WiredTiger5% of free disk space990MB50GB
    MMAPv15% of free disk space990MB50GB

Deployment

  • start each server with config options for replSet
    /usr/bin/mongod --replSet 'myRepl'
  • initiate the replica set on one node - rs.initialize()
  • verify the configuration - rs.conf()
  • add the rest of the nodes - rs.add() on the primary node
    rs.add('node2:27017') , rs.add('node3:27017')
  • check the status of the replica set - rs.status()

Sharding

Components

  • shard/replica set - subset of the sharded data
  • config servers - metadata and config settings
  • mongos - query router, cluster interface
    sh.addShard('shardName')

Shards

  • contains subset of sharded data
  • replica set for redundancy and HA with odd number of voting members
  • primary shard
  • don’t shard collections if dataset fits into single server
  • –shardsvr in config file (port 27018)
  • every xxx has a primary shard per database
  • all non-shared collections will reside on primary shard
Shard keys (and limitations)
  • shard keys are immutable with max size of 512 bytes (can not be updated/changed)
  • must be ascending indexed key or indexed compound keys that exists in every document in the collection
  • cannot be multikey index, a text index or a geospatial index
  • update operations that affect a single document must include the shard key or the _id field
  • no option for sharding if unique indexes on other fields exist
  • no option for second unique index if the shard key is unique index
  • ranged sharding may not distribute the data evenly
  • hashed sharding distributes the data randomly

Config servers

  • config servers as replica set (only 3.4)
  • stores the metadata for sharded cluster in config database
  • authentication configuration information in admin database
  • holds balancer on Primary node (>= 3.4)
  • –configsvr in config file (port 27019)

mongos

  • caching metadata from config servers
  • routes queries to shards
  • no persistent state
  • updates cache on metadata changes
  • holds balancer (mongodb <= 3.2)
  • mongos version 3.4 can not connect to earlier mongod version

Sharding collection

StepCommand
Enable sharding on databasesh.enableSharding('users')
Shard collectionsh.shardCollection('users.history', { user_id : 1 } )
Shard key - indexed key that exists in every documentrange based
sh.shardCollection('users.history', { user_id : 1 } )
hashed based
sh.shardCollection( 'users.history', { user_id • 'hashed' } )
output
markdown source