Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 set up all my indexes?

What is the best practice for this?

1 Answer

0 votes
by (106k points)

To define schema you don't need to create collections in MongoDB. What you can do is just start using them immediately whether they “exist” or not. After that define the “schema”. For that you can use the below-mentioned code:-

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" 

]

Related questions

Browse Categories

...