mongodb

mongodb is a document-based database.

mongosh

shell for mongodb

books

resources

import data

the commandline tool mongoimport can import json files, example:
mongoimport --db dbName --collection collectionName --file fileName.json --jsonArray
if the file contains line-separated objects, drop the --jsonArray parameter.

create database

there is no "create" command in the MongoDB Shell. in order to create a database, you will first need to switch the context to a non-existing database using the use command:
use myshinynewdb
MongoDB only creates the database when you first store data in that database. this data could be a collection or a document.
https://www.mongodb.com/resources/products/fundamentals/create-database

create collection

collections are automatically created as you add documents.

fetch entries

to fetch collection entries use
db.<collection>.find()
db.<collection>.find({<dict>})
db.students.find({'_id': 1}).pretty()

delete entries

db.<collection>.deleteMany([{<dict>, <dict>, ...}])
db.<collection>.deleteOne(<dict>)

insert entries

db.<collection>.insertOne({<dict>})
db.<collection>.insertMany([{<dict>, <dict>, ...}])
db.students.insertMany((function(num) { mylist=[]; for (let i = 0; i < num; ++i) mylist.push({'_id': i, 'name': {'first': 'mahmood'+i, 'last': 'sheikh'}, 'bdate': new Date('2002-1-1'+i), 'courses': [{'ccode': '0', 'cname': 'algebra', 'grade': 10*i}], 'phones': ['052338801'+i, '052449912'+i], 'major': 'computer science', ...(i > 5) && {'minor': 'math'}}); return mylist; })(10));

aggregation

db.companies.aggregate([
    {$match: {founded_year: 2004}},
])
this is equivalent to the following operation using find:
db.companies.find({founded_year: 2004})
now let's add a project stage to our pipeline to reduce the output to just a few fields per document. we'll exclude the "_id" field, but include "name" and "founded_year". our pipeline will be as follows:
db.companies.aggregate([
  {$match: {founded_year: 2004}},
  {$project: {
    _id: 0,
    name: 1,
    founded_year: 1
  }}
])
more operations that can be added to aggregation pipelines can be found at https://www.mongodb.com/docs/manual/reference/operator/aggregation/ and https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/.
[cite:;taken from @mongodb_bradshaw_2019 chapter 7]

grouping aggregation

https://stackoverflow.com/questions/61804268/what-is-root-in-mongodb-aggregate-and-how-it-works
consider the following aggregation pipeline:
db.collection.aggregate([{
    $group: {
        _id: '$history',
        items: {$push: '$$ROOT'}
    }
}])
this causes entries to be grouped by the field history, and items: {$push: '$$ROOT'} is for the entries to be grouped into a subcollection named items, see https://www.mongodb.com/docs/manual/reference/aggregation-variables/ about $$ROOT.
notice the $group also acts as some sort of a $project, as it discards the original element and projects only the specified fields. in the example above, it returns a list of objects with the fields _id and items only.

format float

this can be done using $round

unwind

$unwind takes an array from the input document and creates an output document for each element in that array.

extract a field

extract all _id's from the subcollection data into an array of ids:
db.collection.aggregate([
  {
    $addFields: {
      data: {
        $map: {
          input: "$data",
          as: "data",
          in: "$$data._id"
        }
      }
    }
  }
])

lookup operator

the $lookup operator allows you to read documents from one collection and merge them with documents from another one. much like a left outer join in sql.
i cba manually rewriting the text in the following 2 images: