Introduction MongoDB

2024-06-18 23:18
文章标签 mongodb introduction

本文主要是介绍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:

  • Learn more about the MongoDB Drivers: Start Developing with MongoDB — MongoDB Drivers

  • Dive into the official Getting Started Docs: Getting Started — MongoDB Manual

> 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:

  • The MongoDB Limits: MongoDB Limits and Thresholds — MongoDB Manual

  • The MongoDB Data Types: BSON Types — MongoDB Manual

  • More on Schema Validation: https://docs.mongodb.com

这篇关于Introduction MongoDB的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1073341

相关文章

Go Mongox轻松实现MongoDB的时间字段自动填充

《GoMongox轻松实现MongoDB的时间字段自动填充》这篇文章主要为大家详细介绍了Go语言如何使用mongox库,在插入和更新数据时自动填充时间字段,从而提升开发效率并减少重复代码,需要的可以... 目录前言时间字段填充规则Mongox 的安装使用 Mongox 进行插入操作使用 Mongox 进行更

使用Python实现操作mongodb详解

《使用Python实现操作mongodb详解》这篇文章主要为大家详细介绍了使用Python实现操作mongodb的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、示例二、常用指令三、遇到的问题一、示例from pymongo import MongoClientf

使用MongoDB进行数据存储的操作流程

《使用MongoDB进行数据存储的操作流程》在现代应用开发中,数据存储是一个至关重要的部分,随着数据量的增大和复杂性的增加,传统的关系型数据库有时难以应对高并发和大数据量的处理需求,MongoDB作为... 目录什么是MongoDB?MongoDB的优势使用MongoDB进行数据存储1. 安装MongoDB

生产mongodb 分片与集群 方案

链接:http://my.oschina.net/pwd/blog/411439#navbar-header 注:主要是有一键安装的脚本可以借鉴

mongodb基本命令和Java操作API示例

1.Mongo3.2 java API示例:http://www.cnblogs.com/zhangchaoyang/articles/5146508.html 2.MongoDB基本命:http://www.cnblogs.com/xusir/archive/2012/12/24/2830957.html 3.java MongoDB查询(一)简单查询: http://www.cnblogs

使用jetty和mongodb做个简易文件系统

使用jetty和mongodb做个简易文件系统 - ciaos 时间 2014-03-09 21:21:00   博客园-所有随笔区 原文   http://www.cnblogs.com/ciaos/p/3590662.html 主题  MongoDB  Jetty  文件系统 依赖库: 1,jetty(提供http方式接口) 2,mongodb的java驱动(访问mo

mongodb简单入门

一篇较好的mongodb常用操作命令:http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html mongodb的java操作:http://www.cnblogs.com/cyhe/p/5451421.html

mongodb自启动脚本.md

可粘贴文本(不全): #!/bin/sh##chkconfig: 2345 80 90#description:mongodb#processname:mongodbif test -f /sys/kernel/mm/transparent_hugepage/enabled; thenecho never > /sys/kernel/mm/transparent_hugepage/e

MongoDB学习—(6)MongoDB的find查询比较符

首先,先通过以下函数向BookList集合中插入10000条数据 function insertN(obj,n){var i=0;while(i<n){obj.insert({id:i,name:"bookNumber"+i,publishTime:i+2000})i++;}}var BookList=db.getCollection("BookList")调用函数,这样,BookList

MongoDB学习—(5)修改器$inc,$unset,$push,$pushAll,$allToSet,$pop,$pull,$pullAll

通过db.help()可以查询到关于数据库的操作,一查询发现有很多方法 其中有一个方法为db.getCollection(cname),即通过这一个函数,传入数据库中的一个集合的名称来获取到该集合的一个对象,我们可以编写函数   function insertTenRecord(obj){ var i=0; while(i++<10){ obj.insert({id:i+1,a