Skip to content

Commit 75a7ee6

Browse files
authored
Create 04 MongoDB mongosh Create Collection.md
1 parent ceacaf1 commit 75a7ee6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# MongoDB mongosh Create Collection
2+
3+
In MongoDB, collections are created implicitly when you insert data into them. However, if you want to create an empty collection without inserting any data, you can use the `createCollection` method in the MongoDB shell (`mongosh`).
4+
5+
Here's how you can create an empty collection using `mongosh`:
6+
7+
1. **Open `mongosh` Shell:**
8+
- Open a terminal or command prompt.
9+
- Type `mongosh` and press Enter to start the MongoDB shell.
10+
11+
2. **Switch to a Database (Optional):**
12+
- If you want to work with a specific database, use the `use` command to switch to that database.
13+
14+
```javascript
15+
use mydatabase
16+
```
17+
18+
Replace "mydatabase" with the desired name of your database. If the database doesn't exist, MongoDB will create it when you insert data.
19+
20+
3. **Create an Empty Collection:**
21+
- Use the `createCollection` method to create an empty collection.
22+
23+
```javascript
24+
db.createCollection("myCollection")
25+
```
26+
27+
Replace "myCollection" with the desired name of your collection.
28+
29+
4. **Verify Collection Creation:**
30+
- You can check if the collection has been created by running the following command:
31+
32+
```javascript
33+
show collections
34+
```
35+
36+
This command will display a list of all collections in the current database, and you should see the one you just created.
37+
38+
Remember that in MongoDB, collections are created dynamically when you insert data into them. If you want to explicitly create an empty collection without inserting any documents, you can use the `createCollection` method as shown above.

0 commit comments

Comments
 (0)