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
What does createdCollectionAutomatically mean in MongoDB?
The createdCollectionAutomatically field in MongoDB indicates whether an operation automatically created a collection that didn't exist. When you perform operations like createIndex() or insert() on a non-existing collection, MongoDB creates the collection automatically and returns this boolean flag as true.
Syntax
db.nonExistingCollection.createIndex({fieldName: 1});
// Returns:
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Example 1: Creating Index on Non-Existing Collection
Let us create an index on a collection that doesn't exist ?
db.createCollectionDemo.createIndex({"ClientCountryName": 1});
This will produce the following output ?
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
Example 2: Adding Documents to the Collection
Now let us insert a document into the collection ?
db.createCollectionDemo.insertOne({
"ClientName": "Larry",
"ClientCountryName": "US"
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd2950be3526dbddbbfb612")
}
Verify the Collection
Display all documents from the collection ?
db.createCollectionDemo.find().pretty();
{
"_id": ObjectId("5cd2950be3526dbddbbfb612"),
"ClientName": "Larry",
"ClientCountryName": "US"
}
Key Points
-
createdCollectionAutomatically: trueappears when MongoDB creates a collection during the operation. - If the collection already exists, this field will be
falseor absent. - Common operations that trigger automatic collection creation include
createIndex(),insertOne(), andinsertMany().
Conclusion
The createdCollectionAutomatically field helps you identify when MongoDB automatically created a collection during an operation. This is particularly useful for understanding whether your operation worked on an existing or newly created collection.
