MongoDBとNodeJSの接続
mongodb.connectの概要
このメソッドは、MongoDBサーバーをNodeアプリケーションに接続するために使用されます。これはMongoDBモジュールの非同期メソッドです。
構文
mongodb.connect(path[, callback])
パラメータ
-
•パス –MongoDBサーバーが実際に実行されているサーバーパスとそのポート。
-
•コールバック –この関数は、エラーが発生した場合にコールバックを提供します。
Mongo-DBのインストール
アプリケーションをNodejsに接続する前に、まずMongoDBサーバーをセットアップする必要があります。
-
次のクエリを使用して、npmからmongoDBをインストールします。
npm install mongodb –save
-
次のコマンドを実行して、特定のローカルホストサーバーにmongoDBをセットアップします。これは、MongoDBとの接続を作成するのに役立ちます。
mongod --dbpath=data --bind_ip 127.0.0.1
-
MongodbConnect.jsを作成し、次のコードスニペットをコピーしてそのファイルに貼り付けます。
-
次に、次のコマンドを実行してコードスニペットを実行します。
node MongodbConnect.js
例
// Calling the required MongoDB module.
const MongoClient = require("mongodb");
// Server path
const url = 'mongodb://localhost:27017/';
// Name of the database
const dbname = "Employee";
MongoClient.connect(url, (err,client)=>{
if(!err) {
console.log("successful connection with the server");
}
else
console.log("Error in the connectivity");
}) 出力
C:\Users\tutorialsPoint\> node MongodbConnect.js
(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-deprecation ...` to show where the warning was created)
successful connection with the server. -
MongoDBの条件と連結しますか?
MongoDBの条件と連結するには、$ condを使用し、その中で$concatを操作します。ドキュメントを使用してコレクションを作成しましょう- > db.demo745.insertOne({Value1:"100",Value2:"100"}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6419a930c785c834e554") } > db.demo745
-
MongoDBで$pushを操作する
ドキュメントを使用してコレクションを作成しましょう- > db.demo738.insertOne({Subjects:["C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ead696557bb72a10bcf0661") } > db.demo738.insertOne({Subjects:["MySQL","PL/SQL