Skip to content

Working with MongoDB

Connections to MongoDB

Connection can be made a few different ways:

  • using a MongoDB Shell (that black cmd window in Windows)
  • using a MongoDB Compass application
  • using some own made application, for example from Node based application

You can find out the addresses of these connections at the end of defining the connections in MongoDB Atlas Cloud. Select your Cluster and click Connect button and select some of the connections.

!Image 04

In a below you can see one example connection string from MongoDB Compass to MongoDB Atlas Cloud.

1
mongodb+srv://pasi:******@democluster.brlob.mongodb.net/test

This address can be used in connection with the MongoDB application. Start (if necessary, install the MongoDB Compass application) and use your own connection address. Finally, press the Connect button.

!Image 05

You should see your own database in Mongo Atlas. Please note that you currently do not have a single collection (Collections) in the service. You will learn how to create/edit/delete/... these collections later.

Click on the name of your cluster on the Mongo Atlas Web page and you will see many different views as tabbed options. One of the most important is the "Collections" tab. This tab shows all the collections that were in the database. Now it's still empty. You can bring information to the database or create your own. Let's test a little and create some information.

Select "Add My Own Data" from the view (note that this selection can be different when you are reading this documentation). Add a test database and a persons collection.

!Image 06

Press Create button and a new database will be created in the service. The currently created persons collection is still empty. If you are using the MongoDB Compass application, refresh the view there as well and the empty persons collection will be visible.

Modify content

You can modify your database content a few different ways:

  • using MongoDB Cloud UI
  • using MongoDB Compass application
  • using MongoDB Shell or
  • using your own code from example from Node based app

Next, let's add some data using MongoDB's Atlas view. Select the "Collections" tab from your own cluster and press the "INSERT DOCUMENT" button in the view of the test.persons collection (on the right side, rather in the middle).

!Image 07

Add the values shown in the figure as a document.

!Image 08

Finally, the first document in your collection should be visible.

!Image 09

Tip

Similarly, you can try adding information using the MongoDB Compass application.

Using MongoDB Compas Mongo Shell

The MongoDB Compass application also includes its own Mongo Shell command line window, which is used as shown in the attached image.

!Image 10

This material demonstrates the functionality of MongoDB using the Mongo Shell command line window of the MongoDB Compass application. The presented commands are therefore meant to be written on the command line marked in red above. Mongo Shell includes a full functional environment to JavaScript and connections to selected MongoDB.

Get help

1
2
3
4
5
help
  Shell Help
  use      Set current database
  show   'show databases'/'show dbs': Print
  ....

List all databases

1
2
3
4
show dbs
  test  41kB
  admin   340kB
  local   3.44 GB

Change active database

1
2
use test
  switched to db test

A database switched to active does not have to exist. Such a database is then created if data is added to it. The creation of a new database is therefore done by changing it to active (inventing a name) and adding data to it.

Checking active database

1
2
db
  test

List all collections

1
2
show collections
  persons

CRUD operations

You can create a CRUD = Create, Read, Update, Delete, etc... operations to your MongoDB. Find documentation from here: MongoDB CRUD Operations.

Used query operation will target a specific collection of documents. It can also contain criterias and modifiers.

1
2
db.users.find( { age: {$gt: 18 } } ).sort( {age: 1 } )
   COLLECTION ======= CRITERIA ========= MODIFIER =========

Create

Create or insert operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection. MongoDB provides the following methods to insert documents into a collection:

1
2
3
4
5
6
7
db.persons.insertOne(
  {
    name: "Sue Andersson",
    email: "sue@andrersson.com",
    age: 25
  }
)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
db.persons.insertMany(
  [
    {
    name: "John Smith",
    email: "john@smit.com",
    age: 40
   },
    {
    name: "Anna Matsson",
    email: "anna@matsson.com",
    age: 60
   },
  ]
)

Read

Read operations retrieve documents from a collection; i.e. query a collection for documents. MongoDB provides the following methods to read documents from a collection:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
db.persons.find()

  { _id: ObjectId("63a2c42e427b960c1e14f794"),
    name: 'Sue Andersson',
    email: 'sue@andrersson.com',
    age: 25 }
  { _id: ObjectId("63a2c435427b960c1e14f795"),
    name: 'John Smith',
    email: 'john@smit.com',
    age: 40 }
  { _id: ObjectId("63a2c435427b960c1e14f796"),
    name: 'Anna Matsson',
    email: 'anna@matsson.com',
    age: 60 }
1
2
3
4
5
6
db.persons.find( { age: { $lt: 30 } })

  { _id: ObjectId("63a2c42e427b960c1e14f794"),
    name: 'Sue Andersson',
    email: 'sue@andrersson.com',
    age: 25 }

Note

All MongoDB documents has a own unique _id, which will be generated automatically when document is created.

Update

Update operations modify existing documents in a collection. MongoDB provides the following methods to update documents of a collection:

1
2
3
4
db.persons.updateOne(
  { name: "Sue Andersson" },
  { $set: { email: "sue@domain.com" } }
)
1
2
3
4
db.persons.updateMany(
  { age: { $gt: 35 } },
  { $set: { age: 50 } }
)
1
2
3
4
5
6
7
8
db.persons.replaceOne(
  { name: "Sue Andersson" },
  { 
    name: "Sue Mickelson",
    email: "sue@mickelson.com",
    age: 27
  }
)

Delete

Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection:

1
2
3
db.persons.deleteOne(
  { name: "Sue Andersson" }
)
1
2
3
db.persons.deleteMany(
  { age: { $gt: 35 } }
)

Remove all documents from the collection:

1
db.testData.remove({})

Aggregation Operations

Aggregation operations process multiple documents and return computed results. You can use aggregation operations to:

  • Group values from multiple documents together.
  • Perform operations on the grouped data to return a single result.
  • Analyze data changes over time.

A few examples:

cars.json
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
db.cars.insertMany(
  [
    {
      "name":"Audi",
      "model": "A4",
      "cylinders":4,
      "horsepower":130,
      "acceleration":8,
      "kilometers": 120000,
      "year": 2020,
      "price": 2000
    },
    {
      "name":"Audi",
      "model": "A5",
      "cylinders":4,
      "horsepower":140,
      "acceleration":7,
      "kilometers": 8000,
      "year": 2021,
      "price": 8000
    },
    {
      "name":"Audi",
      "model": "A6",
      "Ccylinders":6,
      "horsepower":240,
      "acceleration":4,
      "kilometers": 16000,
      "year": 2018,
      "price": 20000
    },
    {
      "name":"Opel",
      "model": "Astra",
      "cylinders":4,
      "horsepower":80,
      "acceleration":17,
      "kilometers": 320000,
      "year": 1990,
      "price": 2000
    },
    {
      "name":"Opel",
      "model": "Insignia",
      "cylinders":4,
      "horsepower":105,
      "acceleration":12,
      "kilometers": 120000,
      "year": 1999,
      "price": 12000
    },
    {
      "name":"Volkswagen",
      "model":"Golf",
      "cylinders":4,
      "horsepower":90,
      "acceleration":12,
      "kilometers": 200000,
      "year": 1995,
      "price": 23000
    },
    {
      "name":"Volkswagen",
      "model":"Tiquan",
      "cylinders":4,
      "horsepower":95,
      "acceleration":11,
      "kilometers": 120000,
      "year": 2022,
      "price": 18500
    }
  ]
)

How many kilometers are there in the Audi's.

  • Stage 1: Filter car documents by car name
  • Stage 2: Group remaining documents by car name and calculate total kilometers
1
2
3
4
5
6
7
8
db.cars.aggregate( [
   {
      $match: { "name": "Audi" }
   },
   {
      $group: { _id: "$name", totalKilometers: { $sum: "$kilometers" } }
   }
])
1
{ _id: 'Audi', totalKilometers: 144000 }

Someone wants to bye all cars which are 2020-2022 year model.

  • Stage 1: Filter car documents by year range
  • Stage 2: Group remaining documents by date and calculate total price and count
  • Stage 3: Sort documents by totalPrice in descending order
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
db.cars.aggregate( [
   {
      $match: { "year": { $gte: 2020, $lt: 2023 } }
   },
   {
      $group: { 
        _id: "$name",
        carsValue: { $sum: "$price" }, 
        countCount:{ $count: {}  }     
      }
   },
   {
      $sort: { totalPrice: -1 }
   }
 ])
1
2
{ _id: 'Volkswagen', carsValue: 18500, countCount: 1 }
{ _id: 'Audi', carsValue: 10000, countCount: 2

Find more informations from here:

MongoDB Data Model Design

Effective data models support your application needs. The key consideration for the structure of your documents is the decision to embed or to use references. You can find more information about this from here Data Model Design.

Tip

We are not going a deep level with database designing. Only o few example will be shown.

One-to-Many

One publisher can publish many books. In below, publisher multiple times <- not good.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
   title: "MongoDB: The Definitive Guide",
   author: [ "Kristina Chodorow", "Mike Dirolf" ],
   published_date: ISODate("2010-09-24"),
   pages: 216,
   language: "English",
   publisher: {
              name: "O'Reilly Media",
              founded: 1980,
              location: "CA"
            }
}

{
   title: "50 Tips and Tricks for MongoDB Developer",
   author: "Kristina Chodorow",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English",
   publisher: {
              name: "O'Reilly Media",
              founded: 1980,
              location: "CA"
            }
}

The publisher information is kept in a different collection than the book collection <- better

1
2
3
4
5
6
{
   name: "O'Reilly Media",
   founded: 1980,
   location: "CA",
   books: [12346789, 234567890, ...]
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
{
    _id: 123456789,
    title: "MongoDB: The Definitive Guide",
    author: [ "Kristina Chodorow", "Mike Dirolf" ],
    published_date: ISODate("2010-09-24"),
    pages: 216,
    language: "English"
}

{
   _id: 234567890,
   title: "50 Tips and Tricks for MongoDB Developer",
   author: "Kristina Chodorow",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English"
}

Many-to-Many

A MessageBoard message can have many tags and the same tag can be used in many messages.

1
2
db.messages.insertOne({ title: "My message!", tags: ["followme", "love"] })
db.messages.find({ tags: "followme" })

Many people can participate in a party and a person can participate in many parties.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
let event1 = { _id: "lanparty",
              name: "LAN Party!",
              persons: ["arska", "pasi"] }
let event2 = { _id: "golfparty",
              name: "Golf Party!",
              persons: ["pasi"] }
db.events.insertMany([event1, event2])

let person1 = { _id: "arska", 
                name: "Ari Rantala", 
                events: ["lanparty"]}
let person2 = { _id: "pasi", 
                name: "Pasi Manninen", 
                events: ["lanparty","golfparty"]}
db.persons.insertMany([person1, person2])

db.events.find({_id: {$in: person1.events}})   // (arska) events
db.events.find({_id: {$in: person2.events}})   // (pasi) events
db.persons.find({_id: {$in: event1.persons}})  // (lanparty) persons
db.persons.find({_id: {$in: event2.persons}})  // (golfparty) persons

Read More

Goals of this topic

Understand

  • How to connect MongoDB.
  • How to structure data for MongoDB.
  • How to modify database in MongoDB Atlas.
  • How to use CRUD operations to MongoDB.