Home >Web Front-end >Front-end Q&A >How to implement database addition, deletion, modification and query in nodejs
Database addition, deletion, modification and query in Node.js: Connect to the database: Use MongoClient to connect to the MongoDB database. Insert data: Create a collection and insert data. Delete data: Use deleteOne() to delete data. Update data: Use updateOne() to update data. Query data: Use find() and toArray() to query and obtain data.
Database addition, deletion and modification query in Node.js
1. Connect to the database
<code class="ts">const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const client = new MongoClient(url);</code>
2. Insert data
<code class="ts">const collection = client.db('myDatabase').collection('myCollection'); await collection.insertOne({ name: 'John Doe', age: 30 });</code>
3. Delete data
<code class="ts">await collection.deleteOne({ name: 'John Doe' });</code>
4. Update data
<code class="ts">await collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });</code>
5. Query data
<code class="ts">const cursor = await collection.find({ age: { $gt: 30 } }); const results = await cursor.toArray();</code>
Details:
MongoClient
Connect to the MongoDB database. deleteOne()
and updateOne()
methods to delete and update data. find()
method to query data, and use toArray()
to obtain the results. The above is the detailed content of How to implement database addition, deletion, modification and query in nodejs. For more information, please follow other related articles on the PHP Chinese website!