DEV Community

Cover image for Quick mongo tutorial
Le Vuong
Le Vuong

Posted on • Edited on

2 1

Quick mongo tutorial

Take a quick look at how MongoDB works by following this simple tutorial. All you need is Docker—no additional installations required!

# Run mongo container, expose mongo port
$ docker run --name mongodb -p 27017:27017 -d mongodb/mongodb-community-server:latest

# connect to container to run mongo shell
$ docker exec -it mongodb 

# Now, in the mongo container, run mongosh
$ mongosh

# when connected to mongosh, use `help` to show available commands
test> help

# list dbs
test> show dbs

# Create and switch to db blog if not exist
test> use blog

# Create collection (or `table`)
$ db.createCollection("posts") 

# switch to admin db
$ use admin

# Show first document
$ db.system.version.findOne()

# Insert one docs
$ db.posts.insertOne({})

# Insert mutiple docs
$ db.posts.insertMany([ obj1, obj2 ])

# From your host machine, download sample csv 'citybike'
curl -o citybike.csv https://raw.githubusercontent.com/mongodb-developer/datasets/refs/heads/master/201912-citibike-tripdata-subset.csv

# Copy csv file to mongo container
docker cp citybike.csv mongo:/tmp/citybike.csv

# In mongo container, import sample data to test DB
$ mongoimport --type=csv --headerline /tmp/citybike.csv

# List some rows
$ db.citybike.find({}, {}, {limit: 1})

    [
        {
            _id: ObjectId('671c57a08c5dcbdd8f44b140'),
            tripduration: 602,
            starttime: '2019-12-01 00:00:05.5640',
            stoptime: '2019-12-01 00:10:07.8180',
            'start station id': 3382,
            'start station name': 'Carroll St & Smith St',
            'start station latitude': 40.680611,
            'start station longitude': -73.99475825,
            'end station id': 3304,
            'end station name': '6 Ave & 9 St',
            'end station latitude': 40.668127,
            'end station longitude': -73.98377641,
            bikeid: 41932,
            usertype: 'Subscriber',
            'birth year': 1970,
            gender: 1
        }
    ]
Enter fullscreen mode Exit fullscreen mode

Follow w3schools tutorial in References section if you want to learn more.

References:

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs