Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: How to define a schema?

Tags:

So I have an application that uses MongoDB as a database. The application makes use of a few collections.

When and how should I go about defining the "schema" of the database which includes setting up all the collections as well as indexes needed?

AFAIK, you are unable to define empty collections in MongoDB (correct me if I am wrong, if I can do this it will basically answer this question). Should I insert a dummy value for each collection and use that to setup all my indexes?

What is the best practice for this?

like image 858
Ayrx Avatar asked Jun 08 '13 11:06

Ayrx


People also ask

How do I create a schema in MongoDB Atlas?

Overview. You can create a schema for your App in one of two ways: Create a Realm Object Model from an Atlas App Services Schema: If you have data in your MongoDB Atlas cluster already, MongoDB generates a schema by sampling your data.

How do I get MongoDB schema?

We can get the schema object/first document of the collection using : var schemaObj = db. users. findOne();

What is database schema in MongoDB?

A flexible data model, such as the one found in MongoDB, lets you store or aggregate any type of data and dynamically change schema without application downtime. Data in MongoDB is stored in documents and similarly structured documents are typically organized into collections.


2 Answers

You don't create collections in MongoDB.
You just start using them immediately whether they “exist” or not.

Now to defining the “schema”. As I said, you just start using a collection, so, if you need to ensure an index, just go ahead and do this. No collection creation. Any collection will effectively be created when you first modify it (creating an index counts).

> 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"         } ] 
like image 103
kirelagin Avatar answered Sep 18 '22 00:09

kirelagin


Create empty collection

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

Just you don't really have to, because as someone pointed before, they will get created in real time once you start to interact with the database.

MongoDB is schema-less end of story, but ...

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.

Or if you using node.js server-side you could install mongoose node package which allows you to interact with database in OOP style (Why bother to reinvent the wheel, right?).

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

docs: mongoose NPM installation and basic usage https://www.npmjs.com/package/mongoose mongoose full documentation http://mongoosejs.com

Mongoose use example (defining schema and inserting data)

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); }); 

Wrapping up ...

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.
like image 40
DevWL Avatar answered Sep 20 '22 00:09

DevWL