Node Connection MongoDB

Source: Internet
Author: User
Tags dbase install mongodb mongoclient mongodb mongodb driver create database



node. js Connection MongoDB


Some introduction


MongoDB Https://www.npmjs.com/package/mongodb
GitHub Project Address Https://github.com/mongodb/node-mongodb-native
Owned by the official MongoDB driver
Document http://mongodb.github.io/node-mongodb-native/3.1/api/
Project Home http://mongodb.github.io/node-mongodb-native/
belongs to a wheel that has been built


Installing MongoDB
PS C:\Users\mingm\Desktop\node> npm install mongodb --save
npm WARN saveError ENOENT: no such file or directory, open ‘C:\Users\mingm\Desktop\node\package.json‘
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open ‘C:\Users\mingm\Desktop\node\package.json‘
npm WARN node No description
npm WARN node No repository field.
npm WARN node No README data
npm WARN node No license field.

+ [email protected]
added 7 packages from 5 contributors and audited 7 packages in 108.492s
found 0 vulnerabilities

PS C:\Users\mingm\Desktop\node>
Create a database


Well, because of the various versions, the new parser needs to be used. So you need to set the options parameters
That


useNewUrlParser: true


2.0 of drivers
Older versions are not required.


PS C: \ Users \ mingm \ Desktop \ node> node test.js
Database connection establishment
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
     if (err) {
         throw err;
     }
     console.log ("Database connection established");
     db.close ();
})


A mingming database was created after the connection


> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB
> use local;
switched to db local
>


Queried, not yet, because no data was added to it


Create a Collection


That is, create a table


var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
     if (err) {
         throw err;
     }
     console.log ("Database connection established");
     var dbase = db.db (‘mingming’); // select database as mingming
     dbase.createCollection (‘site’, (err, res) => {// Create database as site collection under mingming
         if (err) {
             throw err;
         }
         console.log (‘Create collection!’);
         db.close ();
     });
});
PS C: \ Users \ mingm \ Desktop \ node> node test.js
Database connection establishment
Create a collection!
PS C: \ Users \ mingm \ Desktop \ node>


Check out this watch.


> show dbs;
admin     0.000GB
config    0.000GB
local     0.000GB
mingming  0.000GB
> use mingming
switched to db mingming
> show ceoolection;
2018-07-31T23:12:55.014+0800 E QUERY    [js] Error: don‘t know how to show [ceoolection] :
[email protected]/mongo/shell/utils.js:1043:11
[email protected]/mongo/shell/utils.js:755:15
@(shellhelp2):1:1
> show collections;
site
> db.site.find();
>
Curd inserting data
PS C: \ Users \ mingm \ Desktop \ node> node test.js
Document inserted successfully!
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
     if (err) {
         throw err;
     }
     var dbo = db.db (‘mingming’);
     var myobj = {name: "mingming", url: "www.iming.info"};
     dbo.collection (‘site’). insertOne (myobj, (err, res) => {// mongodb syntax mingming.site.insert (myObj);
         if (err) {
             throw err;
         }
         console.log ("Document inserted successfully!");
         db.close ();
     });
});
> db.site.find ();
{"_id": ObjectId ("5b607e4d5b8ced1c5cb8a7e4"), "name": "mingming", "url": "www.iming.info"}
{"_id": ObjectId ("5b607e6ee7b6e82d604d5a4d"), "name": "mingming", "url": "www.iming.info"}
>

Inserting more than one data
> db.site.find (). pretty ();
{
        "_id": ObjectId ("5b607e4d5b8ced1c5cb8a7e4"),
        "name": "mingming",
        "url": "www.iming.info"
}
{
        "_id": ObjectId ("5b607e6ee7b6e82d604d5a4d"),
        "name": "mingming",
        "url": "www.iming.info"
}
{
        "_id": ObjectId ("5b6080037aa38239e46c0dc1"),
        "name": "mingming",
        "url": "www.iming.info",
        "type": "cn"
}
{
        "_id": ObjectId ("5b6080037aa38239e46c0dc2"),
        "name": "google",
        "url": "www.google.com.hk",
        "type": "un"
}
{
        "_id": ObjectId ("5b6080037aa38239e46c0dc3"),
        "name": "twitter",
        "url": "www.twitter.com",
        "type": "un"
}
>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
    if (err) {
        throw err;
    }
    var dbo = db.db (‘mingming’);
    var myobj = [
        {name: "mingming", url: "www.iming.info", type: "cn"},
        {name: "google", url: "www.google.com.hk", type: "un"},
        {name: "twitter", url: "www.twitter.com", type: "un"},
    ];
    dbo.collection (‘site’). insertMany (myobj, (err, res) => {// mongodb syntax mingming.site.insert (myObj);
        if (err) {
            throw err;
        }
        console.log ("Document inserted successfully!");
        db.close ();
    });
});
PS C: \ Users \ mingm \ Desktop \ node> node test.js
Document inserted successfully!
PS C: \ Users \ mingm \ Desktop \ node>

Querying data
 PS c:\users\mingm\desktop\node> node test.js[{_id:5b607e4d5b8ced1c5cb8a7e4, Name: ' mingming ', url: ' Www.iming.info '}, {_id:5b607e6ee7b6e82d604d5a4d, Name: ' mingming ', url: ' Www.iming.info '}, {_ID:5B6080037AA 38239E46C0DC1, Name: ' mingming ', url: ' Www.iming.info ', type: ' CN '}, {_ID:5B6080037AA38239E46C0DC2, Name: ' Google ', url: ' www.google.com.hk ', type: ' un '}, {_ID:5B6080037AA38239E46C0DC3, name: ' Twitter ', url: ' www . twitter.com ', type: ' UN '}]ps c:\users\mingm\desktop\node>PS C: \ Users \ mingm \ Desktop \ node> node test.js
[{_id: 5b607e4d5b8ced1c5cb8a7e4,
    name: ‘mingming’,
    url: ‘www.iming.info’},
  {_id: 5b607e6ee7b6e82d604d5a4d,
    name: ‘mingming’,
    url: ‘www.iming.info’},
  {_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘www.iming.info’,
    type: ‘cn’},
  {_id: 5b6080037aa38239e46c0dc2,
    name: ‘google’,
    url: ‘www.google.com.hk’,
    type: ‘un’},
  {_id: 5b6080037aa38239e46c0dc3,
    name: ‘twitter’,
    url: ‘www.twitter.com’,
    type: ‘un‘}]
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
    if (err) {
        throw err;
    }
    var dbo = db.db (‘mingming’);
    dbo.collection (‘site’). find ({}). toArray ((err, result) => {// After using find () to complete the query, use toArray to callback the completed data
        if (err) {
            throw err;
        }
        console.log (result); // Output the result of the callback (because the result is temporarily stored in memory, make sure there is enough memory to save it, or use a stream)
        db.close ();
    });
}) ;;
> db.site.find (). pretty ();
{
        "_id": ObjectId ("5b607e4d5b8ced1c5cb8a7e4"),
        "name": "mingming",
        "url": "www.iming.info"
}
{
        "_id": ObjectId ("5b607e6ee7b6e82d604d5a4d"),
        "name": "mingming",
        "url": "www.iming.info"
}
{
        "_id": ObjectId ("5b6080037aa38239e46c0dc1"),
        "name": "mingming",
        "url": "www.iming.info",
        "type": "cn"
}
{
        "_id": ObjectId ("5b6080037aa38239e46c0dc2"),
        "name": "google",
        "url": "www.google.com.hk",
        "type": "un"
}
{
        "_id": ObjectId ("5b6080037aa38239e46c0dc3"),
        "name": "twitter",
        "url": "www.twitter.com",
        "type": "un"
}
>

Querying data for a specified condition
 PS c:\users\mingm\desktop\node> node test.js[{_id:5b607e4d5b8ced1c5cb8a7e4, Name: ' mingming ', url: ' Www.iming.info '}, {_id:5b607e6ee7b6e82d604d5a4d, Name: ' mingming ', url: ' Www.iming.info '}, {_ID:5B6080037AA 38239E46C0DC1, Name: ' mingming ', url: ' Www.iming.info ', type: ' CN '}]ps C:\users\mingm\desktop\node>pre>PS C: \ Users \ mingm \ Desktop \ node> node test.js
[{_id: 5b607e4d5b8ced1c5cb8a7e4,
    name: ‘mingming’,
    url: ‘www.iming.info’},
  {_id: 5b607e6ee7b6e82d604d5a4d,
    name: ‘mingming’,
    url: ‘www.iming.info’},
  {_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘www.iming.info’,
    type: ‘cn’}]
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
    if (err) {
        throw err;
    }
    var dbo = db.db (‘mingming’);
    var whereStr = {"name": "mingming"}; // query condition
    dbo.collection (‘site’). find (whereStr) .toArray ((err, result) => {// After using find () to complete the query, use toArray to callback the completed data.
        if (err) {
            throw err;
        }
        console.log (result); // Output the result of the callback (because the result is temporarily stored in memory, make sure there is enough memory to save it, or use a stream)
        db.close ();
    });
}) ;;

Update data
PS C: \ Users \ mingm \ Desktop \ node> node test.js
Document updated successfully
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
    if (err) {
        throw err;
    }
    var dbo = db.db (‘mingming’);
    var whereStr = {"name": "mingming"}; // query condition
    var updateStr = {$ set: {"url": "AmingA"}};
    dbo.collection (‘site’). updateOne (whereStr, updateStr, (err, result) => {// After using find () to complete the query, use toArray to callback the completed data.
        if (err) {
            throw err;
        }
        console.log (‘Document updated successfully’); // Output the result of the callback (because the result is temporarily stored in memory, make sure there is enough memory to save it, or use a stream)
        db.close ();
    });
}) ;;
> db.site.find ({"name": "mingming"}). pretty ();
{
        "_id": ObjectId ("5b607e4d5b8ced1c5cb8a7e4"),
        "name": "mingming",
        "url": "AmingA"
}
{
        "_id": ObjectId ("5b607e6ee7b6e82d604d5a4d"),
        "name": "mingming",
        "url": "www.iming.info"
}
{
        "_id": ObjectId ("5b6080037aa38239e46c0dc1"),
        "name": "mingming",
        "url": "www.iming.info",
        "type": "cn"
}
>


Updates for MongoDB


> db.site.update({"name":"mingming"}, {$set: {"url":""}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.site.find({"name":"mingming"});
{ "_id" : ObjectId("5b607e4d5b8ced1c5cb8a7e4"), "name" : "mingming", "url" : "" }
{ "_id" : ObjectId("5b607e6ee7b6e82d604d5a4d"), "name" : "mingming", "url" : "www.iming.info" }
{ "_id" : ObjectId("5b6080037aa38239e46c0dc1"), "name" : "mingming", "url" : "www.iming.info", "type" : "cn" }
>
Update more than one data
PS C: \ Users \ mingm \ Desktop \ node> node test.js
{n: 3, nModified: 3, ok: 1}
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
    if (err) {
        throw err;
    }
    var dbo = db.db (‘mingming’);
    var whereStr = {"name": "mingming"}; // query condition
    var updateStr = {$ set: {"url": ""}};
    dbo.collection (‘site’). updateMany (whereStr, updateStr, (err, result) => {// After using find () to complete the query, use toArray to callback the completed data.
        if (err) {
            throw err;
        }
        console.log (result.result); // Output the result of the callback (because the result is temporarily stored in memory, make sure there is enough memory to save it, or use a stream)
        db.close ();
    });
}) ;;
> db.site.find ({"name": "mingming"});
{"_id": ObjectId ("5b607e4d5b8ced1c5cb8a7e4"), "name": "mingming", "url": ""}
{"_id": ObjectId ("5b607e6ee7b6e82d604d5a4d"), "name": "mingming", "url": ""}
{"_id": ObjectId ("5b6080037aa38239e46c0dc1"), "name": "mingming", "url": "", "type": "cn"}
> 

Delete data


Likewise Deleteone and Deletemany () are not elaborated


Sort


Use sort () to finish sorting


PS C: \ Users \ mingm \ Desktop \ node> node test.js
[{_id: 5b6080037aa38239e46c0dc2,
    name: ‘google’,
    url: ‘www.google.com.hk’,
    type: ‘un’},
  {_id: 5b6080037aa38239e46c0dc3,
    name: ‘twitter’,
    url: ‘www.twitter.com’,
    type: ‘un’},
  {_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘‘,
    type: ‘cn’},
  {_id: 5b607e4d5b8ced1c5cb8a7e4, name: ‘mingming’, url: ‘‘},
  {_id: 5b607e6ee7b6e82d604d5a4d, name: ‘mingming’, url: ‘‘}]
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
    if (err) {
        throw err;
    }
    var dbo = db.db (‘mingming’);
    var mysort = {type: -1}; // descending
    dbo.collection (‘site‘). find (). sort (mysort) .toArray ((err, result) => {
            if (err) {
            throw err;
        }
        console.log (result); // Output the result of the callback (because the result is temporarily stored in memory, make sure there is enough memory to save it, or use a stream)
        db.close ();
    });
}) ;;


MongoDB syntax


> db.site.find({}).sort({type:-1});
{ "_id" : ObjectId("5b6080037aa38239e46c0dc2"), "name" : "google", "url" : "www.google.com.hk", "type" : "un" }
{ "_id" : ObjectId("5b6080037aa38239e46c0dc3"), "name" : "twitter", "url" : "www.twitter.com", "type" : "un" }
{ "_id" : ObjectId("5b6080037aa38239e46c0dc1"), "name" : "mingming", "url" : "", "type" : "cn" }
{ "_id" : ObjectId("5b607e4d5b8ced1c5cb8a7e4"), "name" : "mingming", "url" : "" }
{ "_id" : ObjectId("5b607e6ee7b6e82d604d5a4d"), "name" : "mingming", "url" : "" }
>
Page out


Using limit, paging and sorting are all channels (a concept from Linux)


PS C:\Users\mingm\Desktop\node> node test.js
[ { _id: 5b607e4d5b8ced1c5cb8a7e4, name: ‘mingming‘, url: ‘‘ },
  { _id: 5b607e6ee7b6e82d604d5a4d, name: ‘mingming‘, url: ‘‘ } ]
PS C:\Users\mingm\Desktop\node>
Skips a specified number of bars
PS C: \ Users \ mingm \ Desktop \ node> node test.js
[{_id: 5b6080037aa38239e46c0dc1,
     name: ‘mingming’,
     url: ‘‘,
     type: ‘cn’},
   {_id: 5b6080037aa38239e46c0dc2,
     name: ‘google’,
     url: ‘www.google.com.hk’,
     type: ‘un‘}]
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
     if (err) {
         throw err;
     }
     var dbo = db.db (‘mingming’);
     dbo.collection (‘site‘). find (). skip (2) .limit (2) .toArray ((err, result) => {
             if (err) {
             throw err;
         }
         console.log (result); // Output the result of the callback (because the result is temporarily stored in memory, make sure there is enough memory to save it, or use a stream)
         db.close ();
     });
}) ;;

Random reading of one piece of data
PS C: \ Users \ mingm \ Desktop \ node> node test.js
[{_id: 5b6080037aa38239e46c0dc2,
    name: ‘google’,
    url: ‘www.google.com.hk’,
    type: ‘un‘}]
[{_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘‘,
    type: ‘cn’}]
[{_id: 5b6080037aa38239e46c0dc2,
    name: ‘google’,
    url: ‘www.google.com.hk’,
    type: ‘un‘}]
[{_id: 5b607e6ee7b6e82d604d5a4d, name: ‘mingming’, url: ‘‘}]
[{_id: 5b607e4d5b8ced1c5cb8a7e4, name: ‘mingming’, url: ‘‘}]
[{_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘‘,
    type: ‘cn’}]
[{_id: 5b607e4d5b8ced1c5cb8a7e4, name: ‘mingming’, url: ‘‘}]
[{_id: 5b607e6ee7b6e82d604d5a4d, name: ‘mingming’, url: ‘‘}]
[{_id: 5b607e6ee7b6e82d604d5a4d, name: ‘mingming’, url: ‘‘}]
[{_id: 5b607e4d5b8ced1c5cb8a7e4, name: ‘mingming’, url: ‘‘}]
PS C: \ Users \ mingm \ Desktop \ node> node test.js
[{_id: 5b6080037aa38239e46c0dc2,
    name: ‘google’,
    url: ‘www.google.com.hk’,
    type: ‘un‘}]
[{_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘‘,
    type: ‘cn’}]
[{_id: 5b6080037aa38239e46c0dc3,
    name: ‘twitter’,
    url: ‘www.twitter.com’,
    type: ‘un‘}]
[{_id: 5b607e6ee7b6e82d604d5a4d, name: ‘mingming’, url: ‘‘}]
[{_id: 5b607e6ee7b6e82d604d5a4d, name: ‘mingming’, url: ‘‘}]
[{_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘‘,
    type: ‘cn’}]
[{_id: 5b6080037aa38239e46c0dc1,
    name: ‘mingming’,
    url: ‘‘,
    type: ‘cn’}]
[{_id: 5b607e4d5b8ced1c5cb8a7e4, name: ‘mingming’, url: ‘‘}]
[{_id: 5b6080037aa38239e46c0dc3,
    name: ‘twitter’,
    url: ‘www.twitter.com’,
    type: ‘un‘}]
[{_id: 5b6080037aa38239e46c0dc3,
    name: ‘twitter’,
    url: ‘www.twitter.com’,
    type: ‘un‘}]
PS C: \ Users \ mingm \ Desktop \ node>
var MongoClient = require (‘mongodb’). MongoClient;
var url = "mongodb: //127.0.0.1: 27017 / mingming"; // URL of the connection

MongoClient.connect (url, {useNewUrlParser: true}, (err, db) => {// call the encapsulated connect to establish a connection with MongoDB according to the url
    if (err) {
        throw err;
    }
    var dbo = db.db (‘mingming’);
    for (var i = 0; i <10; i ++) {
        dbo.collection (‘site‘). aggregate ([{$ sample: {size: 1}}]). toArray ((err, result) => {
                if (err) {
                throw err;
            }
            console.log (result); // Output the result of the callback (because the result is temporarily stored in memory, make sure there is enough memory to save it, or use a stream)
        });
    };
    db.close ();
}) ;; 


The same pipes are used


Blog


Www.iming.info



Node Connection MongoDB


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.