Node. Js connected mongo

Some introduction

Mongo https://www.npmjs.com/package/mongodb making project address https://github.com/mongodb/node-mongodb-native belongs to the official mongo drivers Document http://mongodb.github.io/node-mongodb-native/3.1/api/ project homepage http://mongodb.github.io/node-mongodb-native/ belongs to a wheel, It’s already built

Install the mongo

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 ficol3 and Audited 7 packagesin108.492s found 0 back then C:\Users\mingm\Desktop\node>Copy the code

Creating a database

Well, because of the various versions, you need to use a new parser. Therefore, you need to set the parameters of options

useNewUrlParser: true
Copy the code

Older versions of 2.0 drivers are not required.

PS C:\Users\mingm\Desktop\node>Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (err) {
		throw err;
	}
	console.log("Database connection setup");
	db.close();
})
Copy the code

After the connection, a mingming database is created

> show dbs; The admin 0.000 GB config 0.000 GBlocal0.000 GB > uselocal;
switched to db local
>
Copy the code

Query, not yet, because there is no data added to it

Create a collection

That is, create a table

var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (err) {
		throw err;
	}
	console.log("Database connection setup");
	var dbase = db.db('mingming'); // Select mingming dbase.createcollection ('site', (err, res) => {// Create the database as a collection of sites under mingmingif(err) {
			throw err;
		}
		console.log('Create a collection! ');
		db.close();
	});
});
Copy the code
PS C:\Users\mingm\Desktop\node> node test.js PS C:\Users\mingm\Desktop\node>Copy the code

Take a look at this chart

> show dbs; The admin 0.000 GB config 0.000 GBlocal0.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] :
shellHelper.show@src/mongo/shell/utils.js:1043:11
shellHelper@src/mongo/shell/utils.js:755:15
@(shellhelp2):1:1
> show collections;
site
> db.site.find();
>
Copy the code

CURD

Insert data

PS C:\Users\mingm\Desktop\node> node test.js PS C:\Users\mingm\Desktop\node>Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (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();
	});
});
Copy the code
> db.site.find();
{ "_id" : ObjectId("5b607e4d5b8ced1c5cb8a7e4"), "name" : "mingming"."url" : "www.iming.info" }
{ "_id" : ObjectId("5b607e6ee7b6e82d604d5a4d"), "name" : "mingming"."url" : "www.iming.info" }
>
Copy the code

Insert multiple 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"
}
>
Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (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();
	});
});
Copy the code
PS C:\Users\mingm\Desktop\node> node test.js PS C:\Users\mingm\Desktop\node>Copy the code

Query 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: 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>
Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (err) {
		throw err;
	}
	var dbo = db.db('mingming');
	dbo.collection('site').find({}).toarray ((err, result) => {// After using find(), use toArray to complete the callbackif(err) { throw err; } console.log(result); Db.close (); db.close(); db.close(); db.close(); }); });;Copy the code
> 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"
}
>
Copy the code

Query the 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: 5b6080037aa38239e46c0dc1,
    name: 'mingming',
    url: 'www.iming.info'.type: 'cn' } ]
PS C:\Users\mingm\Desktop\node>
Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (err) {
		throw err;
	}
	var dbo = db.db('mingming');
	var whereStr = {"name":"mingming"}; Dbo.collection (dbo.collection('site').find(whereStr). ToArray ((err, result) => {// After using find(), use toArray to complete the callbackif(err) { throw err; } console.log(result); Db.close (); db.close(); db.close(); db.close(); }); });;Copy the code

Update the data

PS C:\Users\mingm\Desktop\node>Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (err) {
		throw err;
	}
	var dbo = db.db('mingming');
	var whereStr = {"name":"mingming"}; Var updateStr = {$set: {"url": "AmingA"}};
	dbo.collection('site').updateOne(whereStr, updateStr, (err, result) => {// After using find(), use toArray to callback the queried dataif (err) {
			throw err;
		}
		console.log('Document updated successfully'); Db.close (); db.close(); db.close(); db.close(); }); });;Copy the code
> 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"
}
>
Copy the code

Mongo’s update

> 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" }
>
Copy the code

Updating Multiple Pieces of Data

PS C:\Users\mingm\Desktop\node> node test.js
{ n: 3, nModified: 3, ok: 1 }
PS C:\Users\mingm\Desktop\node>
Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (err) {
		throw err;
	}
	var dbo = db.db('mingming');
	var whereStr = {"name":"mingming"}; Var updateStr = {$set: {"url": ""}};
	dbo.collection('site').updateMany(whereStr, updateStr, (err, result) => {// After using find(), use toArray to callback the queried dataif(err) { throw err; } console.log(result.result); Db.close (); db.close(); db.close(); db.close(); }); });;Copy the code
> 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" }
>
Copy the code

Delete the data

Likewise deleteOne and deleteMany() are not stated

The sorting

Use sort() to sort

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>
Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (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); Db.close (); db.close(); db.close(); db.close(); }); });;Copy the code

Directing a grammar

> 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" : "" }
>
Copy the code

paging

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>
Copy the code

Skip the specified number of entries

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>
Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (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); Db.close (); db.close(); db.close(); db.close(); }); });;Copy the code

Read a random 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>
Copy the code
var MongoClient = require('mongodb').MongoClient;
var url = "Mongo: / / 127.0.0.1:27017 / mingming." "; Mongoclient.connect (url, {useNewUrlParser: mongoclient.connect) // Mongoclient.connect (url, {useNewUrlParser:true}, (err, db) => {// Call wrapped connect to establish a connection with MongoDB based on the URLif (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); // Outputs the result of the callback (since the result is temporarily stored in memory, make sure there is enough memory for it, or use a stream)}); }; db.close(); });;Copy the code

The same pipes are used

blog

www.iming.info