mongodb添加字段 mongodb 插入表

导读:
MongoDB是一种NoSQL数据库,它使用文档而不是表来存储数据 。在MongoDB中插入文档非常简单 , 只需要调用insertOne或insertMany方法即可 。本文将介绍如何使用MongoDB插入文档 。
【mongodb添加字段 mongodb 插入表】1. 连接到MongoDB
在插入文档之前,我们需要先连接到MongoDB 。可以使用MongoClient对象来连接到MongoDB 。以下是连接代码:
```
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://:@.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
2. 插入单个文档
使用insertOne方法可以向MongoDB中插入单个文档 。以下是插入单个文档的代码:
const insertDocument = function(db, callback) {
const collection = db.collection('documents');
collection.insertOne({a : 1}, function(err, result) {
console.log("Inserted 1 document into the collection");
callback(result);
});
};
3. 插入多个文档
使用insertMany方法可以向MongoDB中插入多个文档 。以下是插入多个文档的代码:
const insertDocuments = function(db, callback) {
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
console.log("Inserted 3 documents into the collection");
总结:
在MongoDB中插入文档非常简单,只需要连接到MongoDB并调用insertOne或insertMany方法即可 。使用MongoDB可以方便地存储和查询数据 。