Common operations of Mongoose

Time:2021-2-20

Mongodb Basics
Use user / / enter the user database
db.auth (“user name”, “password”) / / after setting the account password, it can be used for authentication. First use to enter the database, and then run it. Otherwise, an error will be reported
db.dropDatabase () / / delete the current database
db.user.drop () / / delete a collection called user in the current database
db.user.insert ({“name”: “Zhang Nan”}) / / add a data of Name: Zhang Nan to the user collection
db.user.find ({“name”: “Zhang Nan”}) / / find in the collection name:zhansan Data for
db.user.find (). Count() / / how much data is in the user set
db.student.update ({“name”: “Xiao Ming”}, {$set: {“age”: 16}) / / change the age of those whose name is Xiao Ming to 16 years old
#Pay attention to the complete replacement, and the $set keyword does not appear db.student.update ({“name”: “Xiaoming”}, {“name”: “Daming”, “age”: 17})
db.user.remove ({ age:123 }) / / delete the data with age 123 in the user collection
db.user.ensureIndex ({“user name”: 1}) / / add index for user in user collection
db.user.getIndexes () / / get the index of the user collection
db.user.dropIndex ({“user name”: 1}) / / delete the index of user name in the user collection
db.user.ensureIndex ({“userid”: 1}, {“unique”: true}) / / add the userid as the unique index to the user collection
db.tablename.find().explain( “executionStats” )
Focus on the following values of the output: explain.executionStats.executionTimeMillis

Mongoose is a library encapsulated by mongodb in node
var mongoose=require(“mongoose”)
1. Connection mode
—-No account password set—-
mongoose.connect(“mongodb://localhost:27017/eggxiaomi”)
—-The account password is set—-
mongoose.connect(“mongodb://username:[email protected]:dkh/dbs?authSource=admin”)
//User name: the user name you set, password: password, ipdz: the IP address of the computer, DKH: mongodb port number, DBS: the database you want to operate, admin: the entry database you set when you set the account
//Create user in CMD
db.createUser(
  {
    user: “adminUser”,
    pwd: “adminPass”,
    roles: [ { role: “userAdminAnyDatabase”, db: “admin” } ]
  }
)

2. Define schema
var meSchema=mongoose.Schema({
 name:String,
 age:Number,
 status:{
    type:Number,
    default:1// Set default
 }
})

3. Create data model
var Me= mongoose.model (“me”, meschema, “me”) / / me represents the collection to be operated on

——Find data——
Me.find({},(err,data)=>{
  console.log (data); / / print out data
})

——Add data——
Var u = new me ({/ / instantiate model} to add data
  name:”name”, age:20
})
u.save();

——Modify data——
Me.updateOne({name:”name”},{name:”zhansan”},(err)=>{
 if(err)return;
  console.log (modified successfully)
})

——Delete data——
Me.deleteOne({_id:”‘5b72advdc244acc8d368d”},(err)=>{
 if(err)return;
  console.log (delete successfully)
})
 
4. Mongoose custom modifier
var Newschema=mongoose.Schema({
  name:String,
  age:Number,
  status:{
     type:Number,
     default:1// Set default
  },
  redirect:{
     type:String,
     set(url){
If (! URL) return “” / / determine whether the URL exists
        if( url.indexOf (‘http ‘)! = 0) {/ / determine whether the URL starts with HTTP, and add it automatically
           url=”http://”+url
        }return url;
     }
  }
})
 
5. Mongoose set index
var DeviceSchema = new mongoose.Schema({
  sn: {
    type: Number,
Unique: true / / unique index
   },
   name: {
    type: String,
Index: true / / normal index
}
});

6. Mongodb aggregation pipeline operator
$project / / add, delete and rename fields
$match / / conditional match. Only the documents that meet the conditions can enter the next stage
$limit / / limit the number of results
$skip / / number of skipped documents
$sort / / conditional sort.
$group / / result statistics of condition combination
The $lookup / / $lookup operator is used to introduce data from other sets (associated queries between tables)

#####Common expression operators
$addtoset / / de duplicate the specified fields in the document
$max / / the maximum value of the specified field in the document
$min / / the minimum value of the specified field in the document
$sum / / sum the specified fields in the document
$AVG / / average the specified fields in the document
$GT / / greater than the given value
$LT / / less than the given value
$EQ / / is equal to the given value

—$project modify the text structure, which can be used to set aliases and modify the fields in the document
db.order.aggregate([
 { $project:{ trade_ no:1, price:”$all_ Price “}} / / finding order only returns trade in the document_ No and all_ Price, and all_ Price set the alias to price
])

—$match is used to filter documents. The usage is similar to the parameter in the find() method
db.order.aggregate([
{ $project:{ trade_no:1, all_price:1 } },
{ $match:{“all_ price”:{$ gte:90 }} }  //all_ Price greater than or equal to 90
])

—Group groups the documents in the collection for statistical results.
Count the quantity of each order and group according to the order number
db.order_item.aggregate([
{ $group: {_id: “$order_id”, total: {$sum: “$num”}} }
])

—$sort sorts the documents in the collection
db.order.aggregate([
{ $project:{ trade_no:1, all_price:1 } },
{ $match:{“all_price”:{$gte:90}} },
{ $sort:{“all_ Price “: – 1} / / – 1 means flashback
])

—$limit number of queries per time
db.order.aggregate([
{ $ limit:1 }/ / query one at a time
])

—$skip skip number of documents
db.order.aggregate([
{ $ limit:1 }, / / query one at a time
{ $ skip:1 }/ / skip a piece of data
])

—$lookup table Association
db.order.aggregate([
{
   $lookup:{
       from: “order_ Item “, / / order table and order_ Item table Association
       localField: “order_ ID “, / / order in order table_ ID and the following Association
       foreignField: “order_ id”,  //order_ Order in item table_ id
As: “items” / / the associated data is put in items
   }
}, {
$project:{ trade_ no:1, all_ price:1 , items:1 }/ / display only tradb_ no,all_ price,items
}, {
$match:{“all_ price”:{$ gte:90 }}/ / only show all_ Data with price greater than or equal to 90
}, {
$sort:{“all_ Price “: – 1} / / the data is expressed as all_ Price for flashback
}
])

    
7. Mongoose verification parameters
Required: indicates that the data must be passed in
Max: for number type data, the maximum value
Min: for number type data, minimum value
Enum: enumeration type, data must satisfy enumeration value enum: [‘0 ‘,’1’,’2 ‘]
Match: the added data must conform to the rules of match
MaxLength: maximum length
Minlength: minimum length

Recommended Today

Practice analysis of rust built-in trait: partialeq and EQ

Abstract:Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. This article is shared from Huawei cloud community《Analysis of rust built-in trait: partialeq and EQ》Author: debugzhang Rust uses traits in many places, from simple operator overloading to subtle features like send and sync. Some traits can be automatically […]