Introduction MongoDB

What is MongoDB?

Database solution

How is mongoDB different?

 The Key MongoDB Characteristics

 

link : MongoDB: the application data platform | MongoDB

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Useful Articles/ Docs:

> db.flightData.find().pretty()
{
        "_id" : ObjectId("61b0637ca6a53d11b278e487"),
        "departureAirport" : "MUC",
        "arrivalAirport" : "SFO",
        "aircraft" : "Airbus A380",
        "distance" : 12000,
        "intercontinental" : true,
        "status" : {
                "description" : "on-time",
                "lastUpdated" : "1 hour ago",
                "details" : {
                        "responsible" : "Max Schwarzmueller"
                }
        }
}
{
        "_id" : ObjectId("61b0637ca6a53d11b278e488"),
        "departureAirport" : "LHR",
        "arrivalAirport" : "TXL",
        "aircraft" : "Airbus A320",
        "distance" : 950,
        "intercontinental" : false,
        "status" : {
                "description" : "on-time",
                "lastUpdated" : "1 hour ago",
                "details" : {
                        "responsible" : "Max Schwarzmueller"
                }
        }
}
> db.passengers.find().pretty()
{
        "_id" : ObjectId("61b07613a6a53d11b278e489"),
        "name" : "Max Schwarzmueller",
        "age" : 29
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48a"),
        "name" : "Manu Lorenz",
        "age" : 30
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48b"),
        "name" : "Chris Hayton",
        "age" : 35
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48c"),
        "name" : "Sandeep Kumar",
        "age" : 28
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48d"),
        "name" : "Maria Jones",
        "age" : 30
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48e"),
        "name" : "Alexandra Maier",
        "age" : 27
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48f"),
        "name" : "Dr. Phil Evans",
        "age" : 47
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e490"),
        "name" : "Sandra Brugge",
        "age" : 33
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e491"),
        "name" : "Elisabeth Mayr",
        "age" : 29
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e492"),
        "name" : "Frank Cube",
        "age" : 41
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e493"),
        "name" : "Karandeep Alun",
        "age" : 48
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e494"),
        "name" : "Michaela Drayer",
        "age" : 39
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e495"),
        "name" : "Bernd Hoftstadt",
        "age" : 22
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e496"),
        "name" : "Scott Tolib",
        "age" : 44
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e497"),
        "name" : "Freddy Melver",
        "age" : 41
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e498"),
        "name" : "Alexis Bohed",
        "age" : 35
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e499"),
        "name" : "Melanie Palace",
        "age" : 27
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e49a"),
        "name" : "Armin Glutch",
        "age" : 35
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e49b"),
        "name" : "Klaus Arber",
        "age" : 53
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e49c"),
        "name" : "Albert Twostone",
        "age" : 68
}
Type "it" for more
> db.passengers.updateOne({name:"Albert Twostone"},{$set:{hobbies:["sports","cooking"]}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.passengers.find().pretty()
{
        "_id" : ObjectId("61b07613a6a53d11b278e489"),
        "name" : "Max Schwarzmueller",
        "age" : 29
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48a"),
        "name" : "Manu Lorenz",
        "age" : 30
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48b"),
        "name" : "Chris Hayton",
        "age" : 35
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48c"),
        "name" : "Sandeep Kumar",
        "age" : 28
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48d"),
        "name" : "Maria Jones",
        "age" : 30
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48e"),
        "name" : "Alexandra Maier",
        "age" : 27
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e48f"),
        "name" : "Dr. Phil Evans",
        "age" : 47
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e490"),
        "name" : "Sandra Brugge",
        "age" : 33
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e491"),
        "name" : "Elisabeth Mayr",
        "age" : 29
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e492"),
        "name" : "Frank Cube",
        "age" : 41
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e493"),
        "name" : "Karandeep Alun",
        "age" : 48
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e494"),
        "name" : "Michaela Drayer",
        "age" : 39
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e495"),
        "name" : "Bernd Hoftstadt",
        "age" : 22
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e496"),
        "name" : "Scott Tolib",
        "age" : 44
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e497"),
        "name" : "Freddy Melver",
        "age" : 41
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e498"),
        "name" : "Alexis Bohed",
        "age" : 35
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e499"),
        "name" : "Melanie Palace",
        "age" : 27
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e49a"),
        "name" : "Armin Glutch",
        "age" : 35
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e49b"),
        "name" : "Klaus Arber",
        "age" : 53
}
{
        "_id" : ObjectId("61b07613a6a53d11b278e49c"),
        "name" : "Albert Twostone",
        "age" : 68,
        "hobbies" : [
                "sports",
                "cooking"
        ]
}
Type "it" for more
> db.passengers.find({name:"Albert Twostone"}).pretty()
{
        "_id" : ObjectId("61b07613a6a53d11b278e49c"),
        "name" : "Albert Twostone",
        "age" : 68,
        "hobbies" : [
                "sports",
                "cooking"
        ]
}
> db.passengers.find({name:"Albert Twostone"}).hobbies
> db.passengers.findOne({name:"Albert Twostone"}).hobbies
[ "sports", "cooking" ]
> db.passengers.find({hobbies:"sports"}).pretty()
{
        "_id" : ObjectId("61b07613a6a53d11b278e49c"),
        "name" : "Albert Twostone",
        "age" : 68,
        "hobbies" : [
                "sports",
                "cooking"
        ]
}
> db.flightData.find()
{ "_id" : ObjectId("61b0637ca6a53d11b278e487"), "departureAirport" : "MUC", "arrivalAirport" : "SFO", "aircraft" : "Airbus A380", "distance" : 12000, "intercontinental" : true, "status" : { "description" : "on-time", "lastUpdated" : "1 hour ago", "details" : { "responsible" : "Max Schwarzmueller" } } }
{ "_id" : ObjectId("61b0637ca6a53d11b278e488"), "departureAirport" : "LHR", "arrivalAirport" : "TXL", "aircraft" : "Airbus A320", "distance" : 950, "intercontinental" : false, "status" : { "description" : "on-time", "lastUpdated" : "1 hour ago", "details" : { "responsible" : "Max Schwarzmueller" } } }

> db.flightData.find({"status.description":"on-time"}).pretty()
{
        "_id" : ObjectId("61b0637ca6a53d11b278e487"),
        "departureAirport" : "MUC",
        "arrivalAirport" : "SFO",
        "aircraft" : "Airbus A380",
        "distance" : 12000,
        "intercontinental" : true,
        "status" : {
                "description" : "on-time",
                "lastUpdated" : "1 hour ago",
                "details" : {
                        "responsible" : "Max Schwarzmueller"
                }
        }
}
{
        "_id" : ObjectId("61b0637ca6a53d11b278e488"),
        "departureAirport" : "LHR",
        "arrivalAirport" : "TXL",
        "aircraft" : "Airbus A320",
        "distance" : 950,
        "intercontinental" : false,
        "status" : {
                "description" : "on-time",
                "lastUpdated" : "1 hour ago",
                "details" : {
                        "responsible" : "Max Schwarzmueller"
                }
        }
}
> show dbs
admin    0.000GB
config   0.000GB
flights  0.000GB
local    0.000GB
shop     0.000GB
> use shop
switched to db shop
> db.products.find().pretty()
{
        "_id" : ObjectId("61b002d0a6a53d11b278e483"),
        "name" : "A Book",
        "price" : 12.99
}
{
        "_id" : ObjectId("61b00383a6a53d11b278e484"),
        "name" : "A T-Shirt",
        "price" : 29.99,
        "description" : "This is a high quality T-Shirt"
}
{
        "_id" : ObjectId("61b00455a6a53d11b278e485"),
        "name" : "A Computer",
        "price" : 1229.99,
        "description" : "A high quality computer.",
        "details" : {
                "cpu" : "Intel i7 8770",
                "memory" : 32
        }
}
> db.products.insertOne({title:"T-Shirt",seller:{name:"Max",age:29}})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b083fea6a53d11b278e49e")
}
> db.products.find().pretty()
{
        "_id" : ObjectId("61b002d0a6a53d11b278e483"),
        "name" : "A Book",
        "price" : 12.99
}
{
        "_id" : ObjectId("61b00383a6a53d11b278e484"),
        "name" : "A T-Shirt",
        "price" : 29.99,
        "description" : "This is a high quality T-Shirt"
}
{
        "_id" : ObjectId("61b00455a6a53d11b278e485"),
        "name" : "A Computer",
        "price" : 1229.99,
        "description" : "A high quality computer.",
        "details" : {
                "cpu" : "Intel i7 8770",
                "memory" : 32
        }
}
{
        "_id" : ObjectId("61b083fea6a53d11b278e49e"),
        "title" : "T-Shirt",
        "seller" : {
                "name" : "Max",
                "age" : 29
        }
}
> db.products.find().pretty()
{
        "_id" : ObjectId("61b002d0a6a53d11b278e483"),
        "name" : "A Book",
        "price" : 12.99
}
{
        "_id" : ObjectId("61b00383a6a53d11b278e484"),
        "name" : "A T-Shirt",
        "price" : 29.99,
        "description" : "This is a high quality T-Shirt"
}
{
        "_id" : ObjectId("61b00455a6a53d11b278e485"),
        "name" : "A Computer",
        "price" : 1229.99,
        "description" : "A high quality computer.",
        "details" : {
                "cpu" : "Intel i7 8770",
                "memory" : 32
        }
}
{
        "_id" : ObjectId("61b083fea6a53d11b278e49e"),
        "title" : "T-Shirt",
        "seller" : {
                "name" : "Max",
                "age" : 29
        }
}

> db.products.find()
{ "_id" : ObjectId("61b002d0a6a53d11b278e483"), "name" : "A Book", "price" : 12.99 }
{ "_id" : ObjectId("61b00383a6a53d11b278e484"), "name" : "A T-Shirt", "price" : 29.99, "description" : "This is a high quality T-Shirt" }
{ "_id" : ObjectId("61b00455a6a53d11b278e485"), "name" : "A Computer", "price" : 1229.99, "description" : "A high quality computer.", "details" : { "cpu" : "Intel i7 8770", "memory" : 32 } }
{ "_id" : ObjectId("61b083fea6a53d11b278e49e"), "title" : "T-Shirt", "seller" : { "name" : "Max", "age" : 29 } }
>
> db.products.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 4 }
> db.products.insertOne({name:"A book",price:12.99})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a237a6a53d11b278e49f")
}
> db.products.insertOne({name:"A T-Shirt",price:20.99})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a266a6a53d11b278e4a0")
}
> db.products.find().pretty()
{
        "_id" : ObjectId("61b0a237a6a53d11b278e49f"),
        "name" : "A book",
        "price" : 12.99
}
{
        "_id" : ObjectId("61b0a266a6a53d11b278e4a0"),
        "name" : "A T-Shirt",
        "price" : 20.99
}
> db.products.insertOne({name:"A Computer",price:1299,details:{cpu:"Intel i7 8770"}})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a2e4a6a53d11b278e4a1")
}
> db.products.find().pretty()
{
        "_id" : ObjectId("61b0a237a6a53d11b278e49f"),
        "name" : "A book",
        "price" : 12.99
}
{
        "_id" : ObjectId("61b0a266a6a53d11b278e4a0"),
        "name" : "A T-Shirt",
        "price" : 20.99
}
{
        "_id" : ObjectId("61b0a2e4a6a53d11b278e4a1"),
        "name" : "A Computer",
        "price" : 1299,
        "details" : {
                "cpu" : "Intel i7 8770"
        }
}
> db.products.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 3 }
> db.products.insertOne({name:"A book",price:12.99,details:null})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a35fa6a53d11b278e4a2")
}
> db.products.find().pretty()
{
        "_id" : ObjectId("61b0a35fa6a53d11b278e4a2"),
        "name" : "A book",
        "price" : 12.99,
        "details" : null
}
> db.products.insertOne({name:"A T-Shirt",price:20.99,details:null})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a387a6a53d11b278e4a3")
}
> db.products.insertOne({name:"A Computer",price:1299,details:{cpu:"Intel i7 8770"}})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a38fa6a53d11b278e4a4")
}
> db.products.find().pretty()
{
        "_id" : ObjectId("61b0a35fa6a53d11b278e4a2"),
        "name" : "A book",
        "price" : 12.99,
        "details" : null
}
{
        "_id" : ObjectId("61b0a387a6a53d11b278e4a3"),
        "name" : "A T-Shirt",
        "price" : 20.99,
        "details" : null
}
{
        "_id" : ObjectId("61b0a38fa6a53d11b278e4a4"),
        "name" : "A Computer",
        "price" : 1299,
        "details" : {
                "cpu" : "Intel i7 8770"
        }
}

 

Resetting Your Database

Important: We will regularly start with a clean database server (i.e. all data was purged) in this course.

To get rid of your data, you can simply load the database you want to get rid of (use databaseName) and then execute db.dropDatabase().

Similarly, you could get rid of a single collection in a database via db.myCollection.drop()

 

 

> show dbs
admin    0.000GB
config   0.000GB
flights  0.000GB
local    0.000GB
shop     0.000GB
> use test
switched to db test
> db.dropDatabase()
{ "ok" : 1 }
> use companyData
switched to db companyData
> db.companies.insertOne({name:"Fresh Apples Inc",isStartup: true,employees:33,funding:12345678901234567890,details:{ceo:"Mark Super"},tags:[{title:"perfect"}],foundingData:new Date(),insertedAt:new Timestamp()})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a6b3a6a53d11b278e4a5")
}
> db.companies.findOne()
{
        "_id" : ObjectId("61b0a6b3a6a53d11b278e4a5"),
        "name" : "Fresh Apples Inc",
        "isStartup" : true,
        "employees" : 33,
        "funding" : 12345678901234567000,
        "details" : {
                "ceo" : "Mark Super"
        },
        "tags" : [
                {
                        "title" : "perfect"
                }
        ],
        "foundingData" : ISODate("2021-12-08T12:36:03.929Z"),
        "insertedAt" : Timestamp(1638966963, 1)
}
> db.companies.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.companies.findOne()
null
> db.companies.insertOne({name:"Fresh Apples Inc",isStartup: true,employees:33,funding:12345678901234567890,details:{ceo:"Mark Super"},tags:[{title:"super"},{title:"perfect"}],foundingData:new Date(),insertedAt:new Timestamp()})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a72ba6a53d11b278e4a6")
}
> db.companies.findOne()
{
        "_id" : ObjectId("61b0a72ba6a53d11b278e4a6"),
        "name" : "Fresh Apples Inc",
        "isStartup" : true,
        "employees" : 33,
        "funding" : 12345678901234567000,
        "details" : {
                "ceo" : "Mark Super"
        },
        "tags" : [
                {
                        "title" : "super"
                },
                {
                        "title" : "perfect"
                }
        ],
        "foundingData" : ISODate("2021-12-08T12:38:03.207Z"),
        "insertedAt" : Timestamp(1638967083, 1)
}
> db.numbers.insertOne({a: 1})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a7f0a6a53d11b278e4a7")
}
> db.numbers.findOne()
{ "_id" : ObjectId("61b0a7f0a6a53d11b278e4a7"), "a" : 1 }
> db.stats()
{
        "db" : "companyData",
        "collections" : 2,
        "views" : 0,
        "objects" : 2,
        "avgObjSize" : 134.5,
        "dataSize" : 269,
        "storageSize" : 40960,
        "freeStorageSize" : 16384,
        "indexes" : 2,
        "indexSize" : 40960,
        "indexFreeStorageSize" : 16384,
        "totalSize" : 81920,
        "totalFreeStorageSize" : 32768,
        "scaleFactor" : 1,
        "fsUsedSize" : 153324449792,
        "fsTotalSize" : 254721126400,
        "ok" : 1
}
> db.companies.drop()
true
> db.stats()
{
        "db" : "companyData",
        "collections" : 1,
        "views" : 0,
        "objects" : 1,
        "avgObjSize" : 33,
        "dataSize" : 33,
        "storageSize" : 4096,
        "freeStorageSize" : 0,
        "indexes" : 1,
        "indexSize" : 4096,
        "indexFreeStorageSize" : 0,
        "totalSize" : 8192,
        "totalFreeStorageSize" : 0,
        "scaleFactor" : 1,
        "fsUsedSize" : 153324597248,
        "fsTotalSize" : 254721126400,
        "ok" : 1
}
> db.numbers.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.numbers.insertOne({a: NumberInt(1)})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0a85fa6a53d11b278e4a8")
}
> db.stats()
{
        "db" : "companyData",
        "collections" : 1,
        "views" : 0,
        "objects" : 1,
        "avgObjSize" : 29,
        "dataSize" : 29,
        "storageSize" : 36864,
        "freeStorageSize" : 16384,
        "indexes" : 1,
        "indexSize" : 36864,
        "indexFreeStorageSize" : 16384,
        "totalSize" : 73728,
        "totalFreeStorageSize" : 32768,
        "scaleFactor" : 1,
        "fsUsedSize" : 153268592640,
        "fsTotalSize" : 254721126400,
        "ok" : 1
}
> typeof db.numbers.findOne().a
number
>

Data Types & Limits

MongoDB has a couple of hard limits - most importantly, a single document in a collection (including all embedded documents it might have) must be <= 16mb. Additionally, you may only have 100 levels of embedded documents.

You can find all limits (in great detail) here: MongoDB Limits and Thresholds — MongoDB Manual

 

 

 Understanding Relations

 

 

 > use hospital
switched to db hospital
> db.patients.insertOne({name:"Max",age:29,diseaseSummary:"summary-max-1"})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0ab83a6a53d11b278e4a9")
}
> db.patients.findOne().pretty()
uncaught exception: TypeError: db.patients.findOne(...).pretty is not a function :
@(shell):1:1
> db.patients.findOne()
{
        "_id" : ObjectId("61b0ab83a6a53d11b278e4a9"),
        "name" : "Max",
        "age" : 29,
        "diseaseSummary" : "summary-max-1"
}
> db.diseaseSummaries.insertOne({_id:"summary-max-1",diseases:["cold","broken leg"]})
{ "acknowledged" : true, "insertedId" : "summary-max-1" }
> db.diseaseSummaries.findOne()
{ "_id" : "summary-max-1", "diseases" : [ "cold", "broken leg" ] }
>
>
> db.patients.findOne()
{
        "_id" : ObjectId("61b0ab83a6a53d11b278e4a9"),
        "name" : "Max",
        "age" : 29,
        "diseaseSummary" : "summary-max-1"
}
> db.patients.findOne().diseaseSummary
summary-max-1
> var dsid = db.patients.findOne().diseaseSummary
> dsid
summary-max-1
> db.diseaseSummaries.findOne({_id:dsid})
{ "_id" : "summary-max-1", "diseases" : [ "cold", "broken leg" ] }
> db.patients.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.patients.insertOne({name:"Max",age:29,diseaseSummary:{diseases:["cold","broken leg"]}})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0ad58a6a53d11b278e4aa")
}
> db.patients.findOne()
{
        "_id" : ObjectId("61b0ad58a6a53d11b278e4aa"),
        "name" : "Max",
        "age" : 29,
        "diseaseSummary" : {
                "diseases" : [
                        "cold",
                        "broken leg"
                ]
        }
}

One To One -Using References

> show dbs
admin        0.000GB
companyData  0.000GB
config       0.000GB
flights      0.000GB
hospital     0.000GB
local        0.000GB
shop         0.000GB
> use cardData
switched to db cardData
> db.persons.insertOne({name:"Max",car:{model:"BMW",price:40000}})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0b213a6a53d11b278e4ab")
}
> db.persons.findOne()
{
        "_id" : ObjectId("61b0b213a6a53d11b278e4ab"),
        "name" : "Max",
        "car" : {
                "model" : "BMW",
                "price" : 40000
        }
}
> db.persons.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.persons.insertOne({name:"Max",age:29,salary:3000})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0b295a6a53d11b278e4ac")
}
> db.persons.insertOne({model:"BMW",price:40000,owner:ObjectId("61b0b295a6a53d11b278e4ac")})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0b2f7a6a53d11b278e4ad")
}

 One To Many - Embedded

> show dbs
admin        0.000GB
cardData     0.000GB
companyData  0.000GB
config       0.000GB
flights      0.000GB
hospital     0.000GB
local        0.000GB
shop         0.000GB
> use support
switched to db support
> db.questionThreads.insertOne({creator:"Max",question:"How does that all work?",answers:["q1a1","q1a2"]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0b43da6a53d11b278e4ae")
}
> db.questionThreads.findOne()
{
        "_id" : ObjectId("61b0b43da6a53d11b278e4ae"),
        "creator" : "Max",
        "question" : "How does that all work?",
        "answers" : [
                "q1a1",
                "q1a2"
        ]
}
> db.answers.insertMany([{_id:"q1a1",text:"It works like that."},{_id:"q1a2",text:"Thanks!"}])
{ "acknowledged" : true, "insertedIds" : [ "q1a1", "q1a2" ] }
> db.answers.find()
{ "_id" : "q1a1", "text" : "It works like that." }
{ "_id" : "q1a2", "text" : "Thanks!" }
> db.questionThreads.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.questionThreads.insertOne({creator:"Max",question:"How does that all work?",answers:[{text:"like that."},{text:"Thanks!"}]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0b582a6a53d11b278e4af")
}
> db.questionThreads.findOne()
{
        "_id" : ObjectId("61b0b582a6a53d11b278e4af"),
        "creator" : "Max",
        "question" : "How does that all work?",
        "answers" : [
                {
                        "text" : "like that."
                },
                {
                        "text" : "Thanks!"
                }
        ]
}
> db.questionThreads.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.questionThreads.insertOne({creator:"Max",question:"How does that work?",answers:[{text:"like that."},{text:"Thanks!"}]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0b5baa6a53d11b278e4b0")
}
> db.questionThreads.findOne()
{
        "_id" : ObjectId("61b0b5baa6a53d11b278e4b0"),
        "creator" : "Max",
        "question" : "How does that work?",
        "answers" : [
                {
                        "text" : "like that."
                },
                {
                        "text" : "Thanks!"
                }
        ]
}

One To Many - Using

 

> show dbs
admin        0.000GB
cardData     0.000GB
companyData  0.000GB
config       0.000GB
flights      0.000GB
hospital     0.000GB
local        0.000GB
shop         0.000GB
support      0.000GB
> use cityData
switched to db cityData
> db.cities.insertOne({name:"New York City",coordinates:{lat:21,lng:55}})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0b8a0a6a53d11b278e4b1")
}
> db.cities.findOne()
{
        "_id" : ObjectId("61b0b8a0a6a53d11b278e4b1"),
        "name" : "New York City",
        "coordinates" : {
                "lat" : 21,
                "lng" : 55
        }
}
> db.citizens.insertMany([{name:"Max Schwarzmueller",cityId:ObjectId("61b0b8a0a6a53d11b278e4b1")},{name:"Manuel Lorenz",cityId:ObjectId("61b0b8a0a6a53d11b278e4b1")}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61b0b9dba6a53d11b278e4b2"),
                ObjectId("61b0b9dba6a53d11b278e4b3")
        ]
}
> db.citizens.find()
{ "_id" : ObjectId("61b0b9dba6a53d11b278e4b2"), "name" : "Max Schwarzmueller", "cityId" : ObjectId("61b0b8a0a6a53d11b278e4b1") }
{ "_id" : ObjectId("61b0b9dba6a53d11b278e4b3"), "name" : "Manuel Lorenz", "cityId" : ObjectId("61b0b8a0a6a53d11b278e4b1") }
> db.citizens.find().pretty()
{
        "_id" : ObjectId("61b0b9dba6a53d11b278e4b2"),
        "name" : "Max Schwarzmueller",
        "cityId" : ObjectId("61b0b8a0a6a53d11b278e4b1")
}
{
        "_id" : ObjectId("61b0b9dba6a53d11b278e4b3"),
        "name" : "Manuel Lorenz",
        "cityId" : ObjectId("61b0b8a0a6a53d11b278e4b1")
}
>

Many To Many - Embedded

 > show dbs
admin        0.000GB
cardData     0.000GB
cityData     0.000GB
companyData  0.000GB
config       0.000GB
flights      0.000GB
hospital     0.000GB
local        0.000GB
shop         0.000GB
support      0.000GB
> use shop
switched to db shop
> db.products.find()
{ "_id" : ObjectId("61b0a35fa6a53d11b278e4a2"), "name" : "A book", "price" : 12.99, "details" : null }
{ "_id" : ObjectId("61b0a387a6a53d11b278e4a3"), "name" : "A T-Shirt", "price" : 20.99, "details" : null }
{ "_id" : ObjectId("61b0a38fa6a53d11b278e4a4"), "name" : "A Computer", "price" : 1299, "details" : { "cpu" : "Intel i7 8770" } }
> db.shop.drop()
false
> db.products.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 3 }
> db.products.findOne()
null
> db.products.insertOne({title:"A Book", price:12.99})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0bbf2a6a53d11b278e4b4")
}
> db.products.insertOne({name:"Max",age:29})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0bc13a6a53d11b278e4b5")
}
> db.orders.insertOne({productId:ObjectId("61b0bbf2a6a53d11b278e4b4"),customerId:ObjectId("61b0bc13a6a53d11b278e4b5")})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0bc70a6a53d11b278e4b6")
}
> db.orders.drop()
true
> db.orders.find()
> db.products.find()
{ "_id" : ObjectId("61b0bbf2a6a53d11b278e4b4"), "title" : "A Book", "price" : 12.99 }
{ "_id" : ObjectId("61b0bc13a6a53d11b278e4b5"), "name" : "Max", "age" : 29 }
> db.customers.find()
> db.products.drop()
true
> db.products.insertOne({title:"A Book", price:12.99})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0bd18a6a53d11b278e4b7")
}
> db.customers.insertOne({name:"Max",age:29})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0bd3aa6a53d11b278e4b8")
}
> db.orders.insertOne({productId:ObjectId("61b0bd18a6a53d11b278e4b7"),customerId:ObjectId("61b0bd3aa6a53d11b278e4b8")})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0bd84a6a53d11b278e4b9")
}
>
> db.products.find()
{ "_id" : ObjectId("61b0bd18a6a53d11b278e4b7"), "title" : "A Book", "price" : 12.99 }
> db.customers.find()
{ "_id" : ObjectId("61b0bd3aa6a53d11b278e4b8"), "name" : "Max", "age" : 29 }
> db.customers.updateOne({},{$set:{orders:[{productId: ObjectId("61b0bd18a6a53d11b278e4b7"),quantity: 2}]}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.customers.findOne()
{
        "_id" : ObjectId("61b0bd3aa6a53d11b278e4b8"),
        "name" : "Max",
        "age" : 29,
        "orders" : [
                {
                        "productId" : ObjectId("61b0bd18a6a53d11b278e4b7"),
                        "quantity" : 2
                }
        ]
}
> db.customers.updateOne({},{$set:{orders:[{title:"A Book",price:12.99,quantity: 2}]}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.customers.findOne()
{
        "_id" : ObjectId("61b0bd3aa6a53d11b278e4b8"),
        "name" : "Max",
        "age" : 29,
        "orders" : [
                {
                        "title" : "A Book",
                        "price" : 12.99,
                        "quantity" : 2
                }
        ]
}
> db.products.find()
{ "_id" : ObjectId("61b0bd18a6a53d11b278e4b7"), "title" : "A Book", "price" : 12.99 }
> db.products.findOne()
{
        "_id" : ObjectId("61b0bd18a6a53d11b278e4b7"),
        "title" : "A Book",
        "price" : 12.99
}
>

Many  To Many -Using

> show dbs
admin        0.000GB
cardData     0.000GB
cityData     0.000GB
companyData  0.000GB
config       0.000GB
flights      0.000GB
hospital     0.000GB
local        0.000GB
shop         0.000GB
support      0.000GB
>
>
> use bookRegistry
switched to db bookRegistry
> db.books.insertOne({name:"My favorite Book",authors:[{name:"Max Schwarz",age:29},{name:"Manuel Lor",age:30}]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0c10ea6a53d11b278e4ba")
}
> db.books.find().pretty()
{
        "_id" : ObjectId("61b0c10ea6a53d11b278e4ba"),
        "name" : "My favorite Book",
        "authors" : [
                {
                        "name" : "Max Schwarz",
                        "age" : 29
                },
                {
                        "name" : "Manuel Lor",
                        "age" : 30
                }
        ]
}
> db.authors.insertMany([{name:"Max Schwarz", age: 29, address:{street:"Main"}},{name:"Manuel Lor",age:30,address:{stree:"Tree"}}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61b0c1c6a6a53d11b278e4bb"),
                ObjectId("61b0c1c6a6a53d11b278e4bc")
        ]
}
> db.authors.find().pretty()
{
        "_id" : ObjectId("61b0c1c6a6a53d11b278e4bb"),
        "name" : "Max Schwarz",
        "age" : 29,
        "address" : {
                "street" : "Main"
        }
}
{
        "_id" : ObjectId("61b0c1c6a6a53d11b278e4bc"),
        "name" : "Manuel Lor",
        "age" : 30,
        "address" : {
                "stree" : "Tree"
        }
}
> db.books.updateOne({},{$set:{authors:[ObjectId("61b0c1c6a6a53d11b278e4bb"),ObjectId("61b0c1c6a6a53d11b278e4bc")]}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.books.findOne()
{
        "_id" : ObjectId("61b0c10ea6a53d11b278e4ba"),
        "name" : "My favorite Book",
        "authors" : [
                ObjectId("61b0c1c6a6a53d11b278e4bb"),
                ObjectId("61b0c1c6a6a53d11b278e4bc")
        ]
}

Summarizing Relations

 Using "lookUp()" for Merging Reference Relations

 >
> db.books.aggregate([{$lookup:{from:"authors",localField:"authors",foreignField:"_id",as:"creators"}}]).pretty()
{
        "_id" : ObjectId("61b0c10ea6a53d11b278e4ba"),
        "name" : "My favorite Book",
        "authors" : [
                ObjectId("61b0c1c6a6a53d11b278e4bb"),
                ObjectId("61b0c1c6a6a53d11b278e4bc")
        ],
        "creators" : [
                {
                        "_id" : ObjectId("61b0c1c6a6a53d11b278e4bb"),
                        "name" : "Max Schwarz",
                        "age" : 29,
                        "address" : {
                                "street" : "Main"
                        }
                },
                {
                        "_id" : ObjectId("61b0c1c6a6a53d11b278e4bc"),
                        "name" : "Manuel Lor",
                        "age" : 30,
                        "address" : {
                                "stree" : "Tree"
                        }
                }
        ]
}
>

Planning the Example Excerise

 > show dbs
admin         0.000GB
bookRegistry  0.000GB
cardData      0.000GB
cityData      0.000GB
companyData   0.000GB
config        0.000GB
flights       0.000GB
hospital      0.000GB
local         0.000GB
shop          0.000GB
support       0.000GB
> use blog
switched to db blog
> db.users.insertMany([{name:"Max Schwarzmueller",age: 29, email:"max@test.com"},{name:"Manuel Lorenz",age:30,email:"manu@test.com"}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61b0c778a6a53d11b278e4bd"),
                ObjectId("61b0c778a6a53d11b278e4be")
        ]
}
> db.users.find().pretty()
{
        "_id" : ObjectId("61b0c778a6a53d11b278e4bd"),
        "name" : "Max Schwarzmueller",
        "age" : 29,
        "email" : "max@test.com"
}
{
        "_id" : ObjectId("61b0c778a6a53d11b278e4be"),
        "name" : "Manuel Lorenz",
        "age" : 30,
        "email" : "manu@test.com"
}
> db.posts.insertOne({title:"My first Post!",text:"This is my first post,I hop you like it!",tags:["new","tech"],creator:ObjectId("61b0c778a6a53d11b278e4bd"), comments:[{text:"I like this post!",author:ObjectId("61b0c778a6a53d11b278e4be")}]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0c88ca6a53d11b278e4bf")
}
> db.posts.findOne()
{
        "_id" : ObjectId("61b0c88ca6a53d11b278e4bf"),
        "title" : "My first Post!",
        "text" : "This is my first post,I hop you like it!",
        "tags" : [
                "new",
                "tech"
        ],
        "creator" : ObjectId("61b0c778a6a53d11b278e4bd"),
        "comments" : [
                {
                        "text" : "I like this post!",
                        "author" : ObjectId("61b0c778a6a53d11b278e4be")
                }
        ]
}
>

Understanding Schema Validation

 

 > show dbs
admin         0.000GB
bookRegistry  0.000GB
cardData      0.000GB
cityData      0.000GB
companyData   0.000GB
config        0.000GB
flights       0.000GB
hospital      0.000GB
local         0.000GB
shop          0.000GB
support       0.000GB
> use blog
switched to db blog
> db.users.insertMany([{name:"Max Schwarzmueller",age: 29, email:"max@test.com"},{name:"Manuel Lorenz",age:30,email:"manu@test.com"}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("61b0c778a6a53d11b278e4bd"),
                ObjectId("61b0c778a6a53d11b278e4be")
        ]
}
> db.users.find().pretty()
{
        "_id" : ObjectId("61b0c778a6a53d11b278e4bd"),
        "name" : "Max Schwarzmueller",
        "age" : 29,
        "email" : "max@test.com"
}
{
        "_id" : ObjectId("61b0c778a6a53d11b278e4be"),
        "name" : "Manuel Lorenz",
        "age" : 30,
        "email" : "manu@test.com"
}
> db.posts.insertOne({title:"My first Post!",text:"This is my first post,I hop you like it!",tags:["new","tech"],creator:ObjectId("61b0c778a6a53d11b278e4bd"), comments:[{text:"I like this post!",author:ObjectId("61b0c778a6a53d11b278e4be")}]})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("61b0c88ca6a53d11b278e4bf")
}
> db.posts.findOne()
{
        "_id" : ObjectId("61b0c88ca6a53d11b278e4bf"),
        "title" : "My first Post!",
        "text" : "This is my first post,I hop you like it!",
        "tags" : [
                "new",
                "tech"
        ],
        "creator" : ObjectId("61b0c778a6a53d11b278e4bd"),
        "comments" : [
                {
                        "text" : "I like this post!",
                        "author" : ObjectId("61b0c778a6a53d11b278e4be")
                }
        ]
}
>
>
>
> db.posts.drop()
true
> db.posts.findOne()
null
> db.createCollection("posts",{validator:{$jsonSchema:{bsonType:"object",required:['title','text','creator','comments'],propertises:{title:{bsonType:"string",description:"must be a string and is required"},text:{bsonType:"string",description:"must be a string and is required"},creator:{bsonType:"objectid",description:"must be an objectid and is required"},comments:{bsonType:"array",description:"must be an array and is required",items:{bsonType:"object",description:"must be a string and is required"},author:{bsonType:"objectid",description:"must be a objectid and is required"}}}}}});
{
        "ok" : 0,
        "errmsg" : "Unknown $jsonSchema keyword: propertises",
        "code" : 9,
        "codeName" : "FailedToParse"
}
>
>
> db.createCollection('posts', {
...   validator: {
...     $jsonSchema: {
...       bsonType: 'object',
...       required: ['title', 'text', 'creator', 'comments'],
...       properties: {
...         title: {
...           bsonType: 'string',
...           description: 'must be a string and is required'
...         },
...         text: {
...           bsonType: 'string',
...           description: 'must be a string and is required'
...         },
...         creator: {
...           bsonType: 'objectId',
...           description: 'must be an objectid and is required'
...         },
...         comments: {
...           bsonType: 'array',
...           description: 'must be an array and is required',
...           items: {
...             bsonType: 'object',
...             required: ['text', 'author'],
...             properties: {
...               text: {
...                 bsonType: 'string',
...                 description: 'must be a string and is required'
...               },
...               author: {
...                 bsonType: 'objectId',
...                 description: 'must be an objectid and is required'
...               }
...             }
...           }
...         }
...       }
...     }
...   }
... });

{ "ok" : 1 }
>
>
> db.runCommand({
...   collMod: 'posts',
...   validator: {
...     $jsonSchema: {
...       bsonType: 'object',
...       required: ['title', 'text', 'creator', 'comments'],
...       properties: {
...         title: {
...           bsonType: 'string',
...           description: 'must be a string and is required'
...         },
...         text: {
...           bsonType: 'string',
...           description: 'must be a string and is required'
...         },
...         creator: {
...           bsonType: 'objectId',
...           description: 'must be an objectid and is required'
...         },
...         comments: {
...           bsonType: 'array',
...           description: 'must be an array and is required',
...           items: {
...             bsonType: 'object',
...             required: ['text', 'author'],
...             properties: {
...               text: {
...                 bsonType: 'string',
...                 description: 'must be a string and is required'
...               },
...               author: {
...                 bsonType: 'objectId',
...                 description: 'must be an objectid and is required'
...               }
...             }
...           }
...         }
...       }
...     }
...   },
...   validationAction: 'warn'
... });

{ "ok" : 1 }
>

 

 

Useful Resources & Links

Helpful Articles/ Docs:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值