MongoDB提供了一種靈活而有效的方法來執行創建,讀取,更新,刪除(crud)操作。 讓我們探索如何執行這些操作中的每一個。
插入數據:
> > >將文檔插入MongoDB集合中很簡單。 您可以使用>方法插入單個文檔或insertOne()
插入多個文檔。 這是一個使用MongoDB Shell的示例:insertMany()
// Insert a single document db.myCollection.insertOne( { name: "John Doe", age: 30, city: "New York" } ); // Insert multiple documents db.myCollection.insertMany( [ { name: "Jane Doe", age: 25, city: "London" }, { name: "Peter Jones", age: 40, city: "Paris" } ] );
> node.js或python這樣的驅動程序提供類似的方法,通常具有添加功能以進行錯誤處理和異步操作。例如,在node.js中使用mongodb驅動程序:
const { MongoClient } = require('mongodb'); const uri = "mongodb://localhost:27017"; // Replace with your connection string const client = new MongoClient(uri); async function run() { try { await client.connect(); const database = client.db('myDatabase'); const collection = database.collection('myCollection'); const doc = { name: "Alice", age: 28, city: "Tokyo" }; const result = await collection.insertOne(doc); console.log(`A document was inserted with the _id: ${result.insertedId}`); } finally { await client.close(); } } run().catch(console.dir);
更新數據:
updateOne()
updateMany()
$set
// Update a single document db.myCollection.updateOne( { name: "John Doe" }, { $set: { age: 31 } } ); // Update multiple documents db.myCollection.updateMany( { age: { $lt: 30 } }, { $set: { city: "Unknown" } } );
>更新一個匹配查詢的文檔,而updateOne()
>更新了多個文檔。 您使用updateMany()
>運算符在文檔中修改字段。 這是使用MongoDB shell:
>相似和
>的示例,各種驅動程序中存在。庫提供等效的函數。deleteOne()
deleteMany()
// Delete a single document db.myCollection.deleteOne( { name: "Jane Doe" } ); // Delete multiple documents db.myCollection.deleteMany( { city: "Unknown" } );
從mongodb中檢索數據是使用
方法完成的。 此方法允許使用各種操作員和條件進行功能強大的查詢。
> find()
方法返迴光標,您可以迭代以訪問單個文檔。驅動程序提供了有效處理光標的方法。
// Find all documents db.myCollection.find(); // Find documents where age is greater than 30 db.myCollection.find( { age: { $gt: 30 } } ); // Find documents and project specific fields db.myCollection.find( { age: { $gt: 30 } }, { name: 1, age: 1, _id: 0 } ); // _id: 0 excludes the _id field
find()
中的大型數據集>有效地查詢MongoDB中的大型數據集需要了解索引和查詢優化技術。 索引對於加速查詢至關重要。 在經常查詢的字段上創建索引。 使用適當的查詢運算符,並避免使用
>在MongoDB$where
explain()
中執行CRUD操作時,確保數據完整性的最佳實踐涉及MongoDB中的數據完整性,涉及多個關鍵實踐:
安全:驅動程序通常提供增強的安全功能,例如連接加密和身份驗證。 > 雖然對於學習和實驗是有價值的,但驅動程序對於建立生產準備的應用是必要的,需要構建強大的勞動處理,異常的操作,以及有效的資源管理和優勢管理。
以上是mongodb數據庫怎麼增刪改查的詳細內容。更多資訊請關注PHP中文網其他相關文章!