The assumption is that your MongoDB database is ready to go. Configuring Node.js with Express Framework. To start things off, let’s go ahead and create a fresh Node.js project with the appropriate dependencies. From the command line, execute the following: npm init -y npm install express body-parser mongoose -save. Refer Node.js MongoDB Tutorial to install mongodb package. Get the base URL to MongoDB Service. A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell.
I am able to drop database using node.js but I dont know how to create new database?I want to create monogo database using node.js.Can someone help me about how to create mongo database using node.js?
Robbie12.4k22 gold badges3232 silver badges4242 bronze badges
VKTVKT
2 Answers
David Makogon58.1k1515 gold badges109109 silver badges158158 bronze badges
Tharaka Rumesh JeewanthaTharaka Rumesh Jeewantha
It depends on what you're using to interact with mongo, but you don't usually need to create the database. It's usually just created when you use it in your code.
For example if you use the mongodb native driver:
The driver api docs have lots of examples - http://mongodb.github.io/node-mongodb-native/2.0/api/
RobbieRobbie12.4k22 gold badges3232 silver badges4242 bronze badges
Not the answer you're looking for? Browse other questions tagged node.jsmongodb or ask your own question.
Navigation- Reference >
mongo
Shell Methods >- Database Methods >
- db.createCollection()
Definition¶
db.
createCollection
(name, options)¶Changed in version 3.4: Added support for:
- Creation of views (see also
db.createView()
). - Collation.
Creates a new collection or view.
Because MongoDB creates a collection implicitly when the collectionis first referenced in a command, this method is used primarily forcreating new collections that use specific options. For example, you use
db.createCollection()
to create a capped collection, or to create a new collection that usesdocument validation.db.createCollection()
is a wrapper around the databasecommand create
.The
db.createCollection()
method has the following prototype form:The
db.createCollection()
method has the following parameters:Parameter | Type | Description |
---|---|---|
name | string | The name of the collection to create. |
options | document | Optional. Configuration options for creating a capped collection, forpreallocating space in a new collection, or for creating a view. |
The
options
document contains the following fields:Field | Type | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
capped | boolean | Optional. To create a capped collection,specify true . If you specify true , you must also set a maximumsize in the size field. | ||||||||
autoIndexId | boolean | Optional. Specify false to disable the automatic creation of an index on the_id field.Important Starting in MongoDB 4.0, you cannot set the option autoIndexId to false when creating collections in databases other than thelocal database. | ||||||||
size | number | Optional. Specify a maximum size in bytes for a capped collection. Once acapped collection reaches its maximum size, MongoDB removes the olderdocuments to make space for the new documents. The size field isrequired for capped collections and ignored for other collections. | ||||||||
max | number | Optional. The maximum number of documents allowed in the capped collection. Thesize limit takes precedence over this limit. If a cappedcollection reaches the size limit before it reaches the maximumnumber of documents, MongoDB removes old documents. If you prefer touse the max limit, ensure that the size limit, which isrequired for a capped collection, is sufficient to contain themaximum number of documents. | ||||||||
usePowerOf2Sizes | boolean | Optional. Available for the MMAPv1 storage engine only. Deprecated since version 3.0: For the MMAPv1 storage engine, all collections use the powerof 2 sizes allocation unless the noPadding option is true . The usePowerOf2Sizes optiondoes not affect the allocation strategy. | ||||||||
noPadding | boolean | Optional. Available for the MMAPv1 storage engine only. New in version 3.0: noPadding flag disables the power of 2 sizes allocation for the collection. With noPadding flag set to true, the allocation strategy does not includeadditional space to accommodate document growth, as such, documentgrowth will result in new allocation. Use for collections withworkloads that are insert-only or in-place updates (such asincrementing counters).Defaults to false .Warning Do not set noPadding if the workload includes removes or anyupdates that may cause documents to grow. For more information,see No Padding Allocation Strategy. | ||||||||
storageEngine | document | Optional. Available for the WiredTiger storage engine only. Allows users to specify configuration to the storage engine on aper-collection basis when creating a collection. The value of the storageEngine option should take the following form:Storage engine configuration specified when creating collections arevalidated and logged to the oplog during replication tosupport replica sets with members that use different storageengines. | ||||||||
validator | document | Optional. Allows users to specify validation rules or expressions for the collection. For more information,see Schema Validation. New in version 3.2. The validator option takes a document that specifies thevalidation rules or expressions. You can specify the expressions usingthe same operators as the query operatorswith the exception of $geoNear , $near ,$nearSphere , $text , and $where .Note
| ||||||||
validationLevel | string | Optional. Determines how strictly MongoDB applies thevalidation rules to existing documents during an update.
| ||||||||
validationAction | string | Optional. Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted.New in version 3.2. Important Validation of documents only applies to those documents asdetermined by the validationLevel .
| ||||||||
indexOptionDefaults | document | Optional. Allows users to specify a default configuration for indexes whencreating a collection. The indexOptionDefaults option accepts a storageEngine document, which should take the following form:Storage engine configuration specified when creating indexes arevalidated and logged to the oplog during replication tosupport replica sets with members that use different storageengines. | ||||||||
viewOn | string | The name of the source collection or view from which to create theview. The name is not the full namespace of the collection orview; i.e. does not include the database name and implies the samedatabase as the view to create. You must create views in the samedatabase as the source collection. See also db.createView() .New in version 3.4. | ||||||||
pipeline | array | An array that consists of the aggregation pipeline stage. db.createView creates the view byapplying the specified pipeline to the viewOn collection or view.The view definition is public; i.e. db.getCollectionInfos() and explain operations on the view will include the pipeline thatdefines the view. As such, avoid referring directly to sensitive fieldsand values in view definitions.See also db.createView() . | ||||||||
collation | document | Specifies the default collation for the collection. Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks. The collation option has the following syntax: When specifying collation, the locale field is mandatory; allother collation fields are optional. For descriptions of the fields,see Collation Document.If you specify a collation at the collection level:
If no collation is specified for the collection or for theoperations, MongoDB uses the simple binary comparison used in priorversions for string comparisons. For a collection, you can only specify the collation during thecollection creation. Once set, you cannot modify the collection’sdefault collation. For an example, see Specify Collation. New in version 3.4. | ||||||||
writeConcern | document | Optional. A document that expresses the write concernfor the operation. Omit to use the default writeconcern. When issued on a sharded cluster, mongos converts thewrite concern of thecreate command and its helperdb.createCollection() to 'majority' . |
Access Control¶
If the deployment enforcesauthentication/authorization,
db.createCollection()
requires the following privileges:Required Privileges | |
---|---|
Create a non-capped collection | createCollection on the database, orinsert on the collection to create |
Create a capped collection | convertToCapped for the collectioncreateCollection on the database |
Create a view |
A user with createCollection on the database andfind on the view to create does not havesufficient privileges. |
The
readWrite
built in role includes the requiredprivileges. Alternatively, you cancreate a custom role to supportdb.createCollection()
.The following example uses the
db.createUser()
method tocreate a user in the admin
database with the readWrite
role on the inventory
and employees
database:The created user can execute
db.createCollection()
on the specified databases.For more examples of user creation, see Add Users.![Mongidb Node.js Createcollection Mongidb Node.js Createcollection](/uploads/1/2/4/7/124768305/280331375.png)
Alternatively, you can add the required roles to an existing userusing
db.grantRolesToUser()
. For a tutorial on addingprivileges to an existing database user, seeModify Access for an Existing User.Examples¶
Create a Capped Collection¶
Capped collectionshave maximum size or document counts that prevent them from growingbeyond maximum thresholds. All capped collections must specify a maximumsize and may also specify a maximum document count. MongoDB removesolder documents if a collection reaches the maximum size limit before itreaches the maximum document count. Consider the following example:
This command creates a collection named
log
with a maximum size of 5megabytes and a maximum of 5000 documents.See Capped Collections for moreinformation about capped collections.
Create a Collection with Document Validation¶
Collections with validation compare each inserted or updated documentagainst the criteria specified in the
validator
option. Dependingon the validationLevel
and validationAction
, MongoDB eitherreturns a warning, or refuses to insert or update the document if itfails to meet the specified criteria.The following example creates a
contacts
collection with a JSONSchema validator:Note
MongoDB 3.6 adds the
$jsonSchema
operator to support JSONSchema validation.With the validator in place, the following insert operation fails validation:
The method returns the error in the
WriteResult
:For more information, see Schema Validation. To view thevalidation specifications for a collection, use the
db.getCollectionInfos()
method.Specify Collation¶
Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.
![Mongidb Node.js Createcollection Mongidb Node.js Createcollection](/uploads/1/2/4/7/124768305/411096095.jpg)
You can specify collation at the collection orview level. For example, the followingoperation creates a collection, specifying a collation for thecollection (See Collation Document for descriptions ofthe collation fields):
This collation will be used by indexes and operations that supportcollation unless they explicitly specify a different collation. Forexample, insert the following documents into
myColl
:The following operation uses the collection’s collation:
The operation returns documents in the following order:
The same operation on a collection that uses simple binary collation(i.e. no specific collation set) returns documents in the following order:
See also
Specify Storage Engine Options¶
You can specify collection-specific storage engine configurationoptions when you create a collection with
db.createCollection()
. Consider the following operation:This operation creates a new collection named
users
with aspecific configuration string that MongoDB will pass to thewiredTiger
storage engine. See the WiredTiger documentation ofcollection level optionsfor specific wiredTiger
options.← db.copyDatabase()db.createView() →
© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.