MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications. MongoDB is a product between relational database and non-relational database. Among non-relational databases, it has the most rich functions and is the most like relational database.

Database related Concepts

In a database software can contain multiple data warehouses, in each data warehouse can contain multiple data sets, each data set can contain multiple documents (specific data).

The term explain
database Database, mongoDB database software can be established in multiple databases
collection Collection, a collection of data, can be thought of as an array in JavaScript
document A document, a concrete piece of data, can be thought of as an object in JavaScript
field Fields, property names in documents, can be understood as object properties in JavaScript

Mongoose third Party bag

  • To operate the MongoDB database using Node.js, you need to rely on the third-party Node.js package Mongoose
  • Use the NPM install mongoose command to download

Database connection

Start the mongo

To start mongoDB, run net Start mongoDB in the command line tool. Otherwise, mongoDB cannot be connected.

Connect to the database using the Connect method provided by Mongoose.

We are in a resume file called test.js

// Introduce the mongoose third-party module to operate the database
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
   // The connection succeeded
   .then(() = > console.log('Database connection successful'))
   // Connection failed
   .catch(err= > console.log(err, 'Database connection failed'));
Copy the code

If playground is not available, MongoDB will create the database automatically.

MongoDB add, delete, change and check operations

1. Create collections and documents

The first step is to set rules for the set, and the second step is to create the set. You can create the set by creating an instance of the Mongoose.Schema constructor.

  // Set the set rule
 const courseSchema = new mongoose.Schema({
     name: String.author: String.isPublished: Boolean
 });
  // Create a collection and apply the rules
 const Course = mongoose.model('Course', courseSchema); // courses

Copy the code

The complete code is shown like this

// Introduce the mongoose third-party module to operate the database
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
	// The connection succeeded
	.then(() = > console.log('Database connection successful'))
	// Connection failed
	.catch(err= > console.log(err, 'Database connection failed'));

// Create a collection rule
const courseSchema = new mongoose.Schema({
	name: String.author: String.isPublished: Boolean
});

// Use rules to create collections
// 1. Set name
// 2. Set rules
const Course = mongoose.model('Course', courseSchema) // courses

// Create a document
const course = new Course({
	name: 'node. Js basis'.author: 'wuyuxin'.isPublished: true
});
// Insert documents into the database
course.save();

Copy the code

2. Import data to the mongoDB database

Mongoimport -d database name -c collection name -file Specifies the data file to import

Locate the installation directory of the mongodb database and place the bin directory in the installation directory in the environment variable.

3. Find documents

// Find documents by condition (if condition is empty, find all documents)

Course.find().then(result= > console.log(result))
Copy the code
// Returns a collection of documents
[{
    _id: 5c0917ed37ec9b03c07cf95f,
    name: 'node. Js basis'.author: 'wuyuxin'}, {_id: 5c09dea28acfb814980ff827,
     name: 'Javascript'.author: 'wuyuxin'
}]
Copy the code

// Find documents based on criteria

Course.findOne({name: 'node. Js basis'}).then(result= > console.log(result))
Copy the code

Returned documents

// Return the document
 {
    _id: 5c0917ed37ec9b03c07cf95f,
    name: 'node. Js basis'.author: 'wuyuxin'}Copy the code

There are also some query criteria to look at


 // The match is greater than or less than
 User.find({age: {$gt: 20.$lt: 50}}).then(result= > console.log(result))
 
  // Match contains
User.find({hobbies: {$in: ['Knock code']}}).then(result= > console.log(result))

 // Select the field to query
 User.find().select('name email').then(result= > console.log(result))

 // Sort data by age
 User.find().sort('age').then(result= > console.log(result))

 // skip The number of data skipped limit the number of queries
 User.find().skip(2).limit(2).then(result= > console.log(result))

Copy the code

Here is the more complete code, you can take a look

// Introduce the mongoose third-party module to operate the database
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
	// The connection succeeded
	.then(() = > console.log('Database connection successful'))
	// Connection failed
	.catch(err= > console.log(err, 'Database connection failed'));

// Create a collection rule
const userSchema = new mongoose.Schema({
	name: String.age: Number.email: String.password: String.hobbies: [String]});// Use rules to create collections
const User = mongoose.model('User', userSchema);

// Query all documents in the user set
// User.find().then(result => console.log(result));
// Find documents by the _id field
// User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
The findOne method returns the first document in the current collection by default
// user.findone ({name: 'console.log '}). Then (result => console.log(result))
// Select * from user set where age > 20 and age < 40
// 1.User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result))
// 2. Select from the hobbies field where the hobbies field contains the soccer
/ / User. The find ({hobbies: {$in: [' football ']}}), then (result = > console. The log (result)
// 3. Select the fields to be queried
// User.find().select('name email -_id').then(result => console.log(result))
// 4. Sort by age field
// User.find().sort('age').then(result => console.log(result))
// 5. Sort by age in descending order
// User.find().sort('-age').then(result => console.log(result))
// The query document skips the first two result limits and displays three results
User.find().skip(2).limit(3).then(result= > console.log(result))
Copy the code

4. Delete and update documents

 // Delete a single file
Course.findOneAndDelete({}).then(result= > console.log(result))
 // Delete multiple
User.deleteMany({}).then(result= > console.log(result))
Copy the code

Complete code

// Introduce the mongoose third-party module to operate the database
const mongoose = require('mongoose');
// Database connection
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
	// The connection succeeded
	.then(() = > console.log('Database connection successful'))
	// Connection failed
	.catch(err= > console.log(err, 'Database connection failed'));

// Create a collection rule
const userSchema = new mongoose.Schema({
	name: String.age: Number.email: String.password: String.hobbies: [String]});// Use rules to create collections
const User = mongoose.model('User', userSchema);

// Find a document and delete it
// Returns the deleted document
// If the query condition matches multiple documents, the first matching document will be deleted
// User.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))
// Delete multiple documents
// {} delete all documents
User.deleteMany({}).then(result= > console.log(result))

Copy the code

Well, today’s summary of the content is here, there is a problem I hope you give directions, study together