Experimenting with MongoDB

For a recent prototype, we wanted to bring in a database instead of relying on something like Google Sheets. I’d heard about MongoDB as part of the MERN (MongoDB, Express, React, and Node.js) or MEAN (MongoDB, Express, AngularJS, and Node.js) stacks and felt it was worth a try. In the end, I was very happy with my experience using it for a small prototype application.

Quick Intro to MongoDB


Once you have MongoDB set up in your terminal, you can access it by entering mongo. Then there are a few commands that come in handy:

  • show dbs lists the collections you have in MongoDB. (Collections are sets of records, such as tables in a relational database.)
  • use db_name lets you go to a specific collection.
  • db.db_name.drop(); drops a collection’s records.
    This was particularly helpful when adding and manipulating data in the data structure of my prototype.

Adding and Retrieving Records

A record consists of a JSON object such as {"key": "value"} or {"name": "John"}. When prototyping, we mainly used the insert and find commands to add and retrieve records.

To add records

Entering db.collection_name.insert({"key": "value"}); inserts a record into a collection. This will automatically create a new collection if the one you specify doesn’t already exist.

Let’s create two records by entering:


db.people.inset({"name": "john"});
db.people.inset({"name": "jane"});

If you were to look at the database, the information would be stored in a JSON object as a record like this:

_id: ObjectId(“59d7e4185f9e63c41132a798”)
name: john

To retrieve records

Now enter db.collection_name.find(); to return all records in the collection. To narrow your results, you can add a JSON Object like db.collection_name.find({"key": "value"});. This will find any record in the collection that has the key and value pair.

Entering db.collection_name.find({"name": "jane"}); should return the second object we entered above.  This command would return all records that match a name of jane. The _id is a unique string that is associated with your record when it’s created. You can use this ID to pull out the timestamp from when it was created, which can be helpful.

There is a slew of ways to retrieve data through the use of query selectors and operators.

Reflections

All in all, I was pleasantly surprised how easy it was to bring MongoDB into my prototype. It has great documentation for setup and general support. It’s also written in JavaScript, which means there was no switching cost when moving from writing the application to working on the database.

Items in the database don’t need to be stored any certain way. Like the JavaScript language, it’s very flexible, but this can be tightened down with a schema via Mongo’s Mongoose. To top it off, there is a nice visual tool to view your Collections called MongoDB Compass.

Have you tried MongoDB? I’d love to hear your thoughts.