The MongoJS Cheat Sheet
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. MongoJS and Mongoose 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 MongoJS that will quickly get you oriented MongoJS. We’ll show basic commands and a quick briefing on what each command does.
- Note: To demo we will use a grocery store db
productscollection containing grocery products.
Create a database or switch to a database. ( You should know that the database is not actually created until you create a collection within it )
Display the database you are currently working with
Create a collection and insert a document in it
Get all the documents in a collection
Use the .pretty() to make finds more readable
Find documents with a matching field
Find documents matching multiple fields
Find documents with a matching entry in an array field
Find a document by _id
Update a document. This example will update the soda entry brand. This will only update the first entry where name = “Soda”. If you want to update multiple documents we will show you how to do that next.
Update multiple documents
Add a value to an array field
Delete a document
Delete all documents in a collection
Drop/Delete a collection
Drop/Delete a database
In this cheat sheet we gave you the basic CRUD ( Create, Read, Update, Delete ) commands that will be used with MongoJS. MongoJS is a very easy library to get up and running with so get started and try out some commands. You can get MongoJS from npm by running
npm install mongojs. There are tons of variations and more commands out there for MongoDB but this should serve as a good starting point and reference for anybody using the MongoJS npm library. If you need more help defining a schema for your data, then you might look into the Mongoose library which is great for that scenario. MongoJS provides functions for all MongoDB functionality but you’ll have to manage the schema yourself. It’s more of a low-level library than Mongoose which has it’s advantages and disadvantages depending on your application.
We hope you find this cheat sheet helpful in getting acquainted with MongoJS. If you have any feedback on commands we could add please don’t hesitate to reach out to us.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.Get Started