MongoDB-创建数据库
目录
MongoDB 创建数据库
在 MongoDB 中,创建数据库的过程实际上非常简单。当你第一次向某个数据库插入文档时,该数据库就会自动创建。不过,你也可以使用
use
命令来切换到一个尚未存在的数据库,这会让 MongoDB 准备好接收对该数据库的操作。
下面是如何在 MongoDB 中创建数据库的步骤:
1. 使用 MongoDB Shell 创建数据库
步骤 1: 连接到 MongoDB
首先,打开终端或命令提示符,并使用
mongo
命令连接到 MongoDB 服务器。如果你的 MongoDB 服务器运行在本地默认端口上,可以简单地运行:
mongo
如果你的 MongoDB 服务器运行在其他主机上或使用了非默认端口,可以指定主机名和端口号:
mongo <hostname>:<port>/<database>
步骤 2: 切换到目标数据库
使用
use
命令切换到你想要创建的数据库:
use mynewdb
这会创建一个名为
mynewdb
的新数据库(如果它还不存在的话)。
步骤 3: 插入文档
向数据库中插入一个文档来真正创建它:
db.users.insert({ name: "John Doe", age: 30 })
现在,你已经成功创建了一个名为
mynewdb
的数据库,并在其中插入了一个文档。
2. 使用编程语言创建数据库
你也可以通过编程语言连接到 MongoDB 服务器并创建数据库。以下是使用 Node.js 和 Python 创建数据库的示例。
使用 Node.js 创建数据库
首先确保安装了 MongoDB 的 Node.js 驱动程序:
npm install mongodb
然后,使用以下代码创建一个数据库:
const { MongoClient } = require('mongodb');
// Connection URI
const uri = "mongodb://localhost:27017/mynewdb";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
const db = client.db("mynewdb");
console.log("Connected to MongoDB");
// Perform actions on the collection object
const collection = db.collection("users");
// Insert a document
const result = await collection.insertOne({ name: "Alice", age: 25 });
console.log(result);
// Find documents
const cursor = collection.find({});
await cursor.forEach(doc => console.log(doc));
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
使用 Python 创建数据库
确保安装了
pymongo
:
pip install pymongo
然后,使用以下代码创建一个数据库:
from pymongo import MongoClient
# Connection URI
uri = "mongodb://localhost:27017/mynewdb"
# Create a MongoClient
client = MongoClient(uri)
# Access the database
db = client.mynewdb
print("Connected to MongoDB")
# Access a collection
collection = db.users
# Insert a document
result = collection.insert_one({"name": "Bob", "age": 30})
print("Inserted document:", result.inserted_id)
# Find documents
for doc in collection.find():
print(doc)
总结
在 MongoDB 中创建数据库非常简单。只需要使用
use
命令切换到一个数据库名称,然后插入至少一个文档即可。如果你使用的是编程语言,那么创建数据库的操作通常是通过插入文档来间接完成的。当 MongoDB 第一次看到对一个数据库的引用时,它会自动创建该数据库。