渣渣兔 发表于 2024-9-6 03:20:06

MongoDB 连接

在 MongoDB 中建立连接通常指的是从客户端应用步伐到 MongoDB 服务器的连接。这种连接可以通过 MongoDB 的官方驱动步伐或第三方库来实现。以下是利用不同编程语言连接到 MongoDB 的示例。
1. 利用 MongoDB Shell 连接到 MongoDB

MongoDB Shell 是 MongoDB 提供的一个命令行工具,可以直接用来连接到 MongoDB 服务器。如果你已经安装了 MongoDB,可以通过以下命令连接到当地 MongoDB 服务器:
mongo
如果你的 MongoDB 服务器运行在长途主机上或利用了非默认端口,可以指定主机名和端口号:
mongo
<hostname>:<port>/<database> 比方,连接到运行在 example.com 的 MongoDB 服务器上的 mydb 数据库:
mongo
example.com:27017/mydb 2. 利用 Node.js 连接到 MongoDB

Node.js 的 MongoDB 驱动步伐是一个常用的库,用于从 Node.js 应用步伐连接到 MongoDB 服务器。首先必要安装驱动步伐:
npm install mongo
db 然后,可以利用以下代码连接到 MongoDB 服务器:
const { MongoClient } = require('mongo
db');// Connection URIconst uri = "mongo
db://localhost:27017/mydb";// Create a MongoClient with a MongoClientOptions object to set the Stable API versionconst 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("mydb");    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); 3. 利用 Python 连接到 MongoDB

Python 中有一个非常盛行的 MongoDB 驱动步伐叫做 pymongo
。首先必要安装 pymongo

pip install pymongo

接下来,可以利用以下代码连接到 MongoDB 服务器:
from pymongo
import MongoClient# Connection URIuri = "mongo
db://localhost:27017/mydb"# Create a MongoClientclient = MongoClient(uri)# Access the databasedb = client.mydbprint("Connected to MongoDB")# Access a collectioncollection = db.users# Insert a documentresult = collection.insert_one({"name": "Bob", "age": 30})print("Inserted document:", result.inserted_id)# Find documentsfor doc in collection.find():    print(doc) 4. 利用 Java 连接到 MongoDB

Java 也有一个官方的 MongoDB 驱动步伐。首先必要将驱动步伐添加到项目标依靠中,比方在 Maven 中添加如下依靠:
<dependency>    <groupId>org.mongo
db</groupId>    <artifactId>mongo
db-driver-sync</artifactId>    <version>4.5.2</version></dependency> 然后,可以利用以下代码连接到 MongoDB 服务器:
import com.mongo
db.client.MongoClients;import com.mongo
db.client.MongoClient;import com.mongo
db.client.MongoDatabase;import com.mongo
db.client.MongoCollection;import org.bson.Document;public class App {    public static void main(String[] args) {      // Create a MongoClient      MongoClient mongo
Client = MongoClients.create("mongo
db://localhost:27017/mydb");      // Access the database      MongoDatabase database = mongo
Client.getDatabase("mydb");      System.out.println("Connected to MongoDB");      // Access a collection      MongoCollection<Document> collection = database.getCollection("users");      // Insert a document      Document document = new Document("name", "Charlie")                           .append("age", 35);      collection.insertOne(document);      System.out.println("Inserted document: " + document.toJson());      // Find documents      for (Document doc : collection.find()) {            System.out.println(doc.toJson());      }      // Close the connection      mongo
Client.close();    }} 5. 利用 PHP 连接到 MongoDB

PHP 也支持连接到 MongoDB。首先必要安装 PHP 的 MongoDB 扩展:
pecl install mongo
db 然后,可以利用以下代码连接到 MongoDB 服务器:
<?php$manager = new MongoDB\Driver\Manager("mongo
db://localhost:27017");$dbName = "mydb";$collectionName = "users";// Insert a document$bulk = new MongoDB\Driver\BulkWrite;$bulk->insert(['name' => 'David', 'age' => 40]);$result = $manager->executeBulkWrite($dbName . '.' . $collectionName, $bulk);echo "Inserted document: " . $result->getInsertedCount() . "\n";// Find documents$filter = [];$options = [];$cursor = $manager->executeFind($dbName . '.' . $collectionName, $filter, $options);foreach ($cursor as $document) {    echo json_encode($document) . "\n";}?> 这些示例展示了如何利用不同的编程语言连接到 MongoDB 服务器,并实验基本的操作,如插入和查找文档。每种语言的驱动步伐都提供了更丰富的方法来操作数据和管理连接。根据你的开发情况选择符合的驱动步伐,并参考官方文档以获取更多详细信息。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: MongoDB 连接