Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to create a collection correctly in MongoDB to avoid "ReferenceError: Not defined" error?
To create a collection correctly in MongoDB and avoid "ReferenceError: Not defined" errors, you must use the proper MongoDB database object syntax with createCollection() method.
Syntax
db.createCollection("collectionName");
Example: Creating a Collection
Let us create a collection called "employeeInformation" in the "sample" database ?
use sample;
db.createCollection("employeeInformation");
switched to db sample
{ "ok" : 1 }
Verify Collection Creation
Display all collections in the current database to confirm the collection was created ?
db.getCollectionNames();
[ "arraySizeErrorDemo", "atleastOneMatchDemo", "basicInformationDemo", "combinedAndOrDemo", "convertSQLQueryDemo", "copyThisCollectionToSampleDatabaseDemo", "countOrSizeDemo", "distinctOnMultipleFieldsDemo", "documentWithAParticularFieldValueDemo", "employee", "employeeInformation", "findListOfIdsDemo", "findMimimumElementInArrayDemo", "findSubstring", "getAllRecordsFromSourceCollectionDemo", "getElementWithMaxIdDemo", "insertDocumentWithDateDemo", "internalArraySizeDemo", "keepTwoColumnsUniqueDemo", "largestDocumentDemo", "makingStudentInformationClone", "nestedArrayDemo", "oppositeAddToSetDemo", "prettyDemo", "projectionAnElementDemo", "replacingEntireDocumentDemo", "returnOnlyUniqueValuesDemo", "searchInInnerDemo", "selectItemDemo", "selectWhereInDemo", "sourceCollection", "specificFieldDemo", "studentInformation", "sumOfValueDemo", "sumTwoFieldsDemo", "truncateDemo", "updateFieldIfValueIsGreaterDemo", "updateInformation", "updateSubObjectDemo", "userInformation" ]
Key Points
- Always use
dbobject to reference the current database - Collection names must be enclosed in quotes
- The
createCollection()method returns{ "ok" : 1 }on success
Conclusion
Use db.createCollection("name") with the proper MongoDB database object to avoid reference errors. Always ensure you're connected to the correct database using use databaseName before creating collections.
Advertisements
