programing

MongoDB: 스키마를 어떻게 정의합니까?

css3 2023. 6. 24. 09:26

MongoDB: 스키마를 어떻게 정의합니까?

그래서 저는 MongoDB를 데이터베이스로 사용하는 애플리케이션을 가지고 있습니다.응용 프로그램은 몇 가지 컬렉션을 사용합니다.

필요한 인덱스뿐만 아니라 모든 컬렉션 설정을 포함하는 데이터베이스의 "구성표"를 언제 어떻게 정의해야 합니까?

AFAIK, MongoDB에서 빈 컬렉션을 정의할 수 없습니다(내가 틀렸다면 수정하고, 내가 할 수 있다면 기본적으로 이 질문에 답할 것입니다).각 컬렉션에 더미 값을 삽입하고 모든 인덱스를 설정하는 데 사용해야 합니까?

이를 위한 최선의 방법은 무엇입니까?

MongoDB에서 컬렉션을 만들지 않습니다.
"존재" 여부에 관계없이 즉시 사용하기 시작합니다.

이제 "구성표"를 정의하겠습니다.제가 말씀드렸듯이, 여러분은 그냥 컬렉션을 사용하기 시작하기 때문에, 만약 여러분이 인덱스를 보장해야 한다면, 그냥 이것을 하세요.컬렉션을 만들 수 없습니다.모든 컬렉션은 처음 수정할 때 효과적으로 생성됩니다(인덱스 카운트 생성).

> db.no_such_collection.getIndices()
[ ]
> db.no_such_collection.ensureIndex({whatever: 1})
> db.no_such_collection.getIndices()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "test.no_such_collection",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "whatever" : 1
                },
                "ns" : "test.no_such_collection",
                "name" : "whatever_1"
        }
]

빈 컬렉션 만들기

This is how you could create empty collection in MongoDB using build in interactive terminal:
db.createCollection('someName'); // create empty collection

이전에 누군가가 지적했듯이 데이터베이스와 상호 작용을 시작하면 실시간으로 작성되기 때문에 실제로는 그럴 필요가 없습니다.

MongoDB는 스키마가 없는 이야기지만...

You could create your own class that interacts with mongo Database. In that class you could define rules that have to fulfilled before it can insert data to mongo collection, otherwise throw custom exception.

또는 node.js 서버 측을 사용하는 경우 OOP 스타일로 데이터베이스와 상호 작용할 수 있는 mongoose 노드 패키지를 설치할 수 있습니다(왜 굳이 바퀴를 재설계해야 합니까?).

Mongoose는 애플리케이션 데이터를 모델링하기 위한 간단한 스키마 기반 솔루션을 제공합니다.기본 제공되는 유형 주조, 검증, 쿼리 구축, 비즈니스 로직 후크 등을 즉시 사용할 수 있습니다.

문서: mongoose NPM 설치 및 기본 사용 https://www.npmjs.com/package/mongoose mongoose 전체 문서 http://mongoosejs.com

Mongoose 사용 예제(스키마 정의 및 데이터 삽입)

var personSchema = new Schema({
    name: { type: String, default: 'anonymous' },
    age: { type: Number, min: 18, index: true },
    bio: { type: String, match: /[a-zA-Z ]/ },
    date: { type: Date, default: Date.now },
});

var personModel = mongoose.model('Person', personSchema);
var comment1 = new personModel({
    name: 'Witkor',
    age: '29',
    bio: 'Description',
});

comment1.save(function (err, comment) {
    if (err) console.log(err);
    else console.log('fallowing comment was saved:', comment);
});

마무리 중...

Being able to set schema along with restriction in our code doesn't change the fact that MongoDB itself is schema-less which in some scenarios is actually an advantage. This way if you ever decide to make changes to schema, but you don't bother about backward compatibility, just edit schema in your script, and you are done. This is the basic idea behind the MongoDB to be able to store different sets of data in each document with in the same collection. However, some restriction in code base logic are always desirable.

버전 3.2부터 mongodb는 이제 수집 수준에서 스키마 유효성 검사를 제공합니다.

https://docs.mongodb.com/manual/core/schema-validation/

스키마 생성 예제:

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "address" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               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" ],
               description: "must be a double if the field exists"
            },
            address: {
               bsonType: "object",
               required: [ "city" ],
               properties: {
                  street: {
                     bsonType: "string",
                     description: "must be a string if the field exists"
                  },
                  city: {
                     bsonType: "string",
                     description: "must be a string and is required"
                  }
               }
            }
         }
      }
   }
})

const mongoose = require("mongoose");
const RegisterSchema = mongoose.Schema({
  username: {
    type: String,
    unique: true,
    requied: true,
  },
  email: {
    type: String,
    unique: true,
    requied: true,
  },
  password: {
    type: String,
    requied: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

exports.module = Register = mongoose.model("Register", RegisterSchema);

는 이 튜토리얼을 보았습니다.

MongoDB는 스키마가 없다는 것을 이미 배웠습니다.그러나 실제로 우리는 일종의 "스키마"를 가지고 있으며, 그것은 MongoDB 데이터베이스의 관계를 나타내는 객체의 객체 공간입니다.Ruby가 내가 사용하는 언어이며, 이 답변의 완전성에 대해 어떠한 주장도 하지 않는다는 점에서, 저는 두 가지 소프트웨어를 사용해 볼 것을 추천합니다.

1. ActiveRecord (part of Rails)
2. Mongoid (standalone MongoDB "schema", or rather, object persistence system in Ruby)

하지만 학습 곡선을 기대합니다.저는 다른 사람들이 파이썬과 같은 제 전문 분야가 아닌 다른 훌륭한 언어로 된 솔루션을 알려주기를 바랍니다.

1.Install mongoose: 
        npm install mongoose

2. Set-up connection string and call-backs

 // getting-started.js 

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');


//call-backs

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
  // we're connected!
});

3. Write your schema

var kittySchema = new mongoose.Schema({
  name: String
});

4. Model the schema

var Kitten = mongoose.model('Kitten', kittySchema);

5. Create a document

var silence = new Kitten({ name: 'Tom' });

console.log(silence.name); // Prints 'Tom' to console

// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
  var greeting = this.name
    ? "Meow name is " + this.name
    : "I don't have a name";
  console.log(greeting);
}

    enter code here

var Kitten = mongoose.model('Kitten', kittySchema);
Functions added to the methods property of a schema get compiled into the Model prototype and exposed on each document instance:

var fluffy = new Kitten({ name: 'fluffy' });
fluffy.speak(); // "Meow name is fluffy"

언급URL : https://stackoverflow.com/questions/16998998/mongodb-how-to-define-a-schema