monteecristoo’s blog

https://twitter.com/irakaarozo

mongoDB basic usage

以下 mongo shell 上で

> db

// show databases

> use DB_NAME

// change current database

> db.testMongo.insertOne(

  {

    body: "test mongo operation",

    id: 1

  }

)

// create testMongo collection and insert a document

 

> show collections

// testMongo

 

document model structure

References Data Models (normalized data models)

→ RDBMS風にcollectionを分割してrelated_id でrelational に管理する場合

複雑な many to many relationships に対応できる

多階層のrelationships に対応できる

可読性が下がる

処理を実現するための query が長くなる

 

Embedded Data Models (denormalized data models)

→ embed related data in a single structure or document.

RDBMS では複数にまたがっていたデータが単一の record で管理できるため、query が単純になる

可読性が高い

normalized data models よりデータの duplication が多いのでデータが大きくなる

参考:

Data Modeling Introduction — MongoDB Manual 3.6

Data Model Design — MongoDB Manual 3.6

 

Schema Validation

事前に collection に挿入する data に制限をかける

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "gpa" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            gender: {
               bsonType: "string",
               description: "must be a string and is not required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               exclusiveMaximum: false,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               minimum: 0,
               description: "must be a double and is required"
            }
         }
      }
   }
})

参考:

Schema Validation — MongoDB Manual 3.6

collection 作成後、設定した validation を確認する方法は…

> db.getCollectionInfos()