MongoDB에 생성

blog 데이터베이스 생성, users, posts collection 생성

> use blog

blog> db.users.insertMany([{name:"First",age:20,email:"first@a.com"}, {name:"Second",age:21,email:"second@a.com"}])
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('65e803f125d99817df294c64'),
    '1': ObjectId('65e803f125d99817df294c65')
  }
}

blog> db.users.find()
[
  {
    _id: ObjectId('65e803f125d99817df294c64'),
    name: 'First',
    age: 20,
    email: 'first@a.com'
  },
  {
    _id: ObjectId('65e803f125d99817df294c65'),
    name: 'Second',
    age: 21,
    email: 'second@a.com'
  }
]

blog> db.posts.insertOne({title:"My first Post", text:"Thist is my first post", tags:["new", "tech"], creator:ObjectId('65e803f125d99817df294c65'), comments:[{text:"I like this post",author:ObjectId('65e803f125d99817df294c64')}]})
{
  acknowledged: true,
  insertedId: ObjectId('65e804b225d99817df294c66')
}

blog> db.posts.find()
[
  {
    _id: ObjectId('65e804b225d99817df294c66'),
    title: 'My first Post',
    text: 'Thist is my first post',
    tags: [ 'new', 'tech' ],
    creator: ObjectId('65e803f125d99817df294c65'),
    comments: [
      {
        text: 'I like this post',
        author: ObjectId('65e803f125d99817df294c64')
      }

 

Schema Validation

 

db.createCollection('posts',
{ 
    validator: { 
        $jsonSchema: { 
            bsonType: 'object', 
            required: ['title', 'text', 'creator', 'comments'], 
            properties: {
                titile: {
                    bsonType: "string",
                    description: "must be a string and required"
                },
                text: {
                    bsonType: "string",
                    description: "must be a string and required"
                },
                creator: {
                    bsonType: "objectId",
                    description: "must be a objectid and required"
                },
                comment: {
                    bsonType: "array",
                    description: "must be a array and required",
                    items: {
                        bsonType: "object",
                        required: ["text", "author"],
                        properties: {
                            text: {
                                bsonType: "string",
                                description: "must be a array and required"
                            },
                            author: {
                                bsonType: "objectId",
                                description: "must be a array and required"
                            }
                        }
                    }
                }
            }
        }
    }
});

 

데이터 모델리 시 고려해야 할 사항

- 데이터 페치 형식

- 얼마나 자주 데이터가 페치/변경되는지

-  데이터 저장 건수

- 데이터 연관성

- 데이터 중복 허용

- 데이터와 저장공간 한계

 

 

Useful Resources & Links

Helpful Articles/ Docs:

+ Recent posts