Getting started with MongoDB and simple cases

MongoDB

1. What is MongoDB

  • MongoDB is a database based on distributed file storage. It is a database system designed for the rapid development of Internet web applications.
  • The design goal of MongoDB is to be minimalist, flexible, and to be part of the web application stack.
  • MongoDB's data model is document-oriented. The so-called document is a structure similar to JSON. It is simple to understand that there are various JSONs stored in the MongoDB database.

2. Three concepts

  • Database
    -a database is a warehouse, in which collections can be stored
  • Collection
    -A collection is similar to an array, and documents can be stored in a collection.
  • Document
    -the smallest unit in the document database, the content we store and manipulate is all documents.

3. Basic instructions

  • In MongoDB, neither database nor collection need to be created manually. When we create a document, if the collection or database does not exist, the database and collection will be created automatically.
  • show dbs: show all current databases
  • use database: enter the specified database
  • db: db represents the current database
  • show collections: Show all collections in the database.
  • For details of MongoDB's CRUD operation, please see the official document
3.1, insert operation
  • db.collection.insert({key:value}), insert one or more documents into the collection
  • When we insert a document into the collection, if the _id attribute is not specified for the document, the database will automatically add the _id attribute to the document as the unique identifier of the document (the id is generated by the timestamp and machine code),
  • We can call ObjectId() to generate

Insert picture description here

3.2, find the collection

db.collection.find()

  • find() is used to query the documents that meet the conditions in the collection,
  • find() can accept all documents in a collection
  • {} means to query all documents in the collection
  • {Attribute: Value} The query attribute is the specified value document
  • db.collections.find((field)), returns a piece of data

Insert picture description here

  • What db.collections.findOne() returns is an object. If you click the attribute at the back, the attribute will be found

Insert picture description here

  • db.stus.count() / length() query how many pieces of data are in the collection
3.3, modify operation
  • db.collection.update{query object, new object}
  • update() replaces old objects with new objects by default
  • If you need to modify the specified attribute instead of replacing it, you need to use the "modification operator" to complete the modification. $set can be used to modify the specified attribute in the file.

Insert picture description here
This will blank out the unmatched ones

Insert picture description here
The modification operator should be used.

Insert picture description hereInsert picture description here

  • $unset means to delete a field, the usage is similar to $set
  • db.collections.updateMany(): Modify multiple eligible documents at the same time.
  • db.collection.updateOne(): Modify a document that meets the conditions.
  • db.collection.updateOne()
3.4, delete documents
  • db.collection.remove(): Delete documents based on conditions. The method of passing conditions is the same as find. Passing a true as the second parameter will delete only one. Same as deleteOne.
  • db.collection.deteleOne()
  • db.collection.deleteMany()

Insert picture description here

  • db.collection.drop(): Drop the collection.

4. The relationship between documents (non-relational databases)

  • One-to-one: (one to one) In MongoDB, one-to-one relationships can be embodied in the form of embedded documents.
    Insert picture description hereInsert picture description here

  • One to many: (one to many) / many to one (many to one) One-to-many relationship can also be mapped through embedded documents

Insert picture description here

  • Many to many: (many to many)

Insert picture description here

5. Sort and projection

  • The query document is sorted by the value of _id by default (ascending order)
  • sort () can be used to specify the sorting rules of the document, sort() needs to pass an object to specify the sorting rules.
  • For example: db.stus.find({}).sort({field:1}) , if it is positive 1 means ascending order, descending order -1
  • limit skip sort can be called in any order
  • When querying, you can set the projection of the query result in the position of the second parameter: **db.stus.find({},(name:1._id:0))** This means that only the name is displayed, by default In this case, if _id:0 is not added, the ID will be displayed.

6、Mongose

Insert picture description here

  • You can create a schema for the document.
  • Can be validated for objects/documents in the model.
  • Data can be converted to an object model by type.
  • You can use middleware to apply business logic hooks.
  • It is easier than Node's native MongoDB driver.
6.1, mongoose provides us with several new objects
  • Schema (Schema Object): Schema object definition constrains the document structure in the database
  • Model: The Model object represents all the documents in the collection, which is equivalent to the collection collection in the MongoDB database
  • Document: Document represents a specific document in the collection, which is equivalent to a specific document in the collection
6.2, install and test mongoose

Mongoose document address: mongoose document

  • Create a directory and a package.json file

Insert picture description here

  • If there is an error: you need to change the directory name above, not mongoose, and also change the name in the package.json file.

Insert picture description here

  • After successful installation

Insert picture description here

  • If it is a successful project, there will be a corresponding directory import
    Insert picture description here
6.21. Introduce mongoose into the project
var mongoose = require("mongoose");
6.22, connect to MongooDB database
//官网示例:
const mongoose = require('mongoose');//项目中引入mongoose
mongoose.connect('mongodb://localhost:27017/test', {
    
    useNewUrlParser: true});

const Cat = mongoose.model('Cat', {
    
     name: String });

const kitty = new Cat({
    
     name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));

Create a js file, modify and write the above code accordingly, and then run it. as follows

//在这里插入代码片
var mongoose = require('mongoose');//项目中引入mongoose

mongoose.connect('mongodb://localhost:27017/mongoose_test', {
    
    useNewUrlParser: true});

mongoose.connection.once("open",function(){
    
    
    console.log("数据库连接成功")
});

If the project cannot run the js file, please install Node.js first and install the Node.js plug-in in idea. There is also a detailed installation tutorial in another article of mine.
-Monitor the connection status of the MongoDB database

  • In the mongoose object, there is an attribute called connection, which represents that the database connection can monitor the connection and disconnection of data monitoring by monitoring the state of the object.
  • The time when the database connection is successful mongoose.connection.once("open",function(){}); /The event of database disconnection mongoose.connection.once("close",function(){});
6.23. Disconnect the database connection: mongoose.disconnect()
6.3, Schema and Model

Create another js file in the project for testing.

  • mongoose_demo.js
    -Schema: official website example
  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;

  var blogSchema = new Schema({
    
    
    title:  String, // String is shorthand for {type: String}
    author: String,
    body:   String,
    comments: [{
    
     body: String, date: Date }],
    date: {
    
     type: Date, default: Date.now },
    hidden: Boolean,
    meta: {
    
    
      votes: Number,
      favs:  Number
    }
  });
  • model: Official example
mongoose.model(modelName, schema):
 var Blog = mongoose.model('Blog', blogSchema);
  // ready to go!
  • document content:
var mongoose = require('mongoose');//项目中引入mongoose

mongoose.connect('mongodb://localhost:27017/mongoose_test', {
    
    useNewUrlParser: true});

mongoose.connection.once("open",function(){
    
    
    console.log("数据库连接成功")
});


//将mongoose.Schema 赋值给一个变量
var Schema = mongoose.Schema;

//创建 Schema(模式)对象
var stuSchema = new Schema({
    
    
   name:String,
   age:Number,
   gender:{
    
    
       type:String,
       default:"female"
   },
    address:String
});


//通过Schema来创建Model
//Model代表的是数据库的集合,通过Model才能对数据库进行操作
//mongoose.model(modelName,schema);
//modelName 就是要映射的集合名,mongoose会自动将集合名变为复数
var StuModel = mongoose.model("student",stuSchema);

//创建完model后依然不能再数据库中创建,因为需要创建文档
//向数据库中插入一个文档
//StuModel.create(doc,function(err){});
StuModel.create({
    
    
    name:"孙悟空",
    age: 18,
    gender:"male",
    address: "花果山"

},function(err){
    
    
    if (!err){
    
    
        console.log("插入成功!!!");
    }
});

  • Click to run, and then there will be relevant data!
    Insert picture description here
  • View the database, related data has been created
    Insert picture description here
6.4, Model method

Related method: Official document Model method.
With Model, we can add, delete, modify, and check data.

  • Create
    Model.create(doc(s),(callback)) to create one or more documents and add them to the database
    • Parameters:
      doc(s): It can be a document object or a document object's mobile phone to open
      callback: the callback function that jumps when the operation is completed
// pass a spread of docs and a callback
Candy.create({
    
     type: 'jelly bean' }, {
    
     type: 'snickers' }, function (err, jellybean, snickers) {
    
    
  if (err) // ...
});

// pass an array of docs
var array = [{
    
     type: 'jelly bean' }, {
    
     type: 'snickers' }];
Candy.create(array, function (err, candies) {
    
    
  if (err) // ...

  var jellybean = candies[0];
  var snickers = candies[1];
  // ...
});

// callback is optional; use the returned promise if you like:
var promise = Candy.create({
    
     type: 'jawbreaker' });
promise.then(function (jawbreaker) {
    
    
  // ...
})
  • Query
    Model.find/findOne/findMany(conditions,[projection],[options].[callback]);
    -parameter
    conditions: query condition
    projection: projection, the field to be obtained
    -two ways (requires name, not id Example)
    {name:1,_id:0}
    “name -_id”
    options: query options (skip limit) set the number of skips or limit how many
    callbacks are displayed : callback function, the query result will be returned through the callback function, the callback function must If you don’t pass the callback function, it won’t be queried at all.
// named john and at least 18
MyModel.find({
    
     name: 'john', age: {
    
     $gte: 18 }});

// executes, passing results to callback
MyModel.find({
    
     name: 'john', age: {
    
     $gte: 18 }}, function (err, docs) {
    
    });

// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({
    
     name: /john/i }, 'name friends', function (err, docs) {
    
     })

// passing options
MyModel.find({
    
     name: /john/i }, null, {
    
     skip: 10 })

// passing options and executes
MyModel.find({
    
     name: /john/i }, null, {
    
     skip: 10 }, function (err, docs) {
    
    });

// executing a query explicitly
var query = MyModel.find({
    
     name: /john/i }, null, {
    
     skip: 10 })
query.exec(function (err, docs) {
    
    });

// using the promise returned from executing a query
var query = MyModel.find({
    
     name: /john/i }, null, {
    
     skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {
    
    });

Insert picture description here

  • Modify
    Model.find / One / Many (Conditions, [Projection], [Options] [the callback].);
    - Parameter
    conditions: query
    dos: modified object
    options: Configuration parameters
    callback: callback function,
MyModel.update({
    
     age: {
    
     $gt: 18 } }, {
    
     oldEnough: true }, fn);

const res = await MyModel.update({
    
     name: 'Tobi' }, {
    
     ferret: true });
res.n; // Number of documents that matched `{ name: 'Tobi' }`
// Number of documents that were changed. If every doc matched already
// had `ferret` set to `true`, `nModified` will be 0.
res.nModified;

Insert picture description here

  • 删除
    Model.remove(conditions,[callback])
    Model.delete/deleteManty(conditions,[callback])
Character.deleteOne({
    
     name: 'Eddard Stark' }, function (err) {
    
    });

Insert picture description here

6.5, document method
  • Document has a one-to-one correspondence with the documents in the collection. Document is an instance of Model, and the result of querying through Model is Document

Insert picture description hereJust create an object and not insert it into the database.
Related methods: document method

6.6 Modularization of Model
  • Create a new js file and define a module.
var mongoose = require('mongoose');//项目中引入mongoose

mongoose.connect('mongodb://localhost:27017/mongoose_test', {
    
    useNewUrlParser: true});

mongoose.connection.once("open",function(){
    
    
    console.log("数据库连接成功")
});
  • Create a new file to define Schmea
var mongoose = require('mongoose');//项目中引入mongoose
var Schema = mongoose.Schema;
var stuSchema = new Schema({
    
    
    name:String,
    age:Number,
    gender:{
    
    
        type:String,
        default:"female"
    },
    address:String
});
var StuModel = mongoose.model("student",stuSchema);
model.exports = StuModel;  //将其暴露出去,方便调用
  • Create a new js file and start mongoose
require("上个文件的相对路径");
var Student = require("student文件路径");

So far, the simple introduction to MongoDB has been finished.

Guess you like

Origin blog.csdn.net/JISOOLUO/article/details/103492983
Recommended