「Node.js」insertMany関数でMongoDBのテーブルに複数データを挿入するサンプル

2020年11月23日

構文
変数.collection(“コレクション名").insertMany(オブジェクト, function(err, res) {
some code
}
サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("testdb");
var myobj = [
{ name: 'user001', email: '11@example.com', type: 'typeA'},
{ name: 'user002', email: '12@example.com', type: 'typeB'},
{ name: 'user003', email: '13@example.com', type: 'typeC'}
];
dbo.collection("usercollect").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("insert collect : " + res.insertedCount);
db.close();
});
});
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) { if (err) throw err; var dbo = db.db("testdb"); var myobj = [ { name: 'user001', email: '11@example.com', type: 'typeA'}, { name: 'user002', email: '12@example.com', type: 'typeB'}, { name: 'user003', email: '13@example.com', type: 'typeC'} ]; dbo.collection("usercollect").insertMany(myobj, function(err, res) { if (err) throw err; console.log("insert collect : " + res.insertedCount); db.close(); }); });
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("testdb");
    var myobj =  [
        { name: 'user001', email: '11@example.com', type: 'typeA'},
        { name: 'user002', email: '12@example.com', type: 'typeB'},
        { name: 'user003', email: '13@example.com', type: 'typeC'}
       ];
    dbo.collection("usercollect").insertMany(myobj, function(err, res) {
        if (err) throw err;
        console.log("insert collect : " + res.insertedCount);
        db.close();
    });
});

 

Node.js

Posted by arkgame