preface
Little girl recently began to switch to the service end, due to the lack of talent and learning, often operate the database, have to refer to the document, today, empty, little woman to sort out this article, I hope to help the rookie like me.
Operation database, in the final analysis is to add, delete, change, check. For today’s article, let’s start with the most used query.
The query
Query methods
The most basic methods used in Mongoose query are find, findOne and findById. Find queries all values that meet the conditions and returns an array. FindOne and findById take a value that meets the conditions and return an object.
Model.find(conditions, [fields], [options], [callback])
Note: conditions query condition, fields field to return, Options, callback callback function
Select * from user table where name, gender, residential address, creation time are displayed in reverse order
/ / object writing userModel. Find ({' name ':' Joe '}, {" name ": 1," sex ": 1, the" region ": 1," createBy ": 1," _id ": 0}, {limit: 2, skip: 1, Sort :' -createby.createtime '}) // UserModel. Find ({' name ':' Joe '}, {" name ": 1," sex ": 1, the" region ": 1," createBy ": 1," _id ": 0}). Skip (7). The limit (2). Sort ({' createBy. Create Time' : -1})Copy the code
Common query conditions
Mongoose query criteria are simply the addition of mongodb conditional operators to find or findOne methods
The common mongodb conditional operators are as follows:
$gt > $gte > = $lt > $lte < = $ne > = $nin $all = $regex; $size = $maxDistance; Distance (based on LBS) $mod mod operation $NEAR neighborhood query $elemMatch $within $box $within $elemMatch $within $box Rectangular range (based on LBS) $center range query, circular range (based on LBS) $centerSphere range query, spherical range (based on LBS) $slice query elements in the field set (e.g., from the NTH to the MTH element after the number)Copy the code
Show and hide fields
There are two types of specification in Mongoose, string specification and object specification.
1. When a string is specified, a hyphen (-) is added to the front of the excluded field.
Model.find({},'age');
Model.find({},'-name');
Copy the code
2. When the object form is specified, 1 indicates inclusion and 0 indicates exclusion.
Model.find({}, { age: 1 });
Model.find({}, { name: 0 });
Copy the code
Paging query
- The values can be ASC, desc, Ascending, descending, 1, or -1.
- Limit: Specifies the maximum number of results to return.
- Skip: Specifies the number of documents to skip
- Lean: Return normal JS objects instead of Mongoose Documents. It is suggested that data returned to the front end without special processing by Mongoose should be converted into ordinary JS objects using this method.
Note: When both sort and limit are used together, the order in which they are called is not important.
Model.find(conditions).skip(pageTotal * pageNum).limit(pageTotal).sort({'_id':-1}).exec(cb);
Copy the code
PageTotal is the number of pages displayed on each page, pageNum is the number of pages, cb is the callback function,sort({‘_id’:-1}) is sorted by _id in reverse order
Query non-empty fields
Model.find(conditions:{$exists:true})
Model.find(conditions:{$ne:null})
Copy the code
Array object lookup
data
{author: [{name: "dora", age: 18 },{name: "wang", age: 16 }]}
Copy the code
1. Accurate query
Model.find({ author: { name: "dora", age: 18 } })
Copy the code
2. Click syntax query
Model.find({ 'author.age': { $gte: 18 } })
Copy the code
3.$elemMatch matches all search conditions
Model.find({ "author": {$elemMatch: {name: 'dora', age:{ $lt: 18 }}})
// []
Copy the code
Array subscript query
data
{ year: [ 2018, 2019 ] }
{ year: [ 2017, 2019, 2020 ] }
{ year: [ 2016, 2020 ] }
Copy the code
The second value of the array year is greater than 2019.
Model.find({ 'year.1': { $gt: 2019 } }) // { "_id" : ... , "year" : [ 2016, 2020 ] }Copy the code
Lookup of nested object fields
data
{
name: { first: "dora", last: "wang" }
}
Copy the code
1. The sequence and fields must be the same.
Model.find({name: {last: "wang", first: "DORA"}}) // [Copy the code
2. Use dot syntax to match nested fields, where field names must be enclosed in quotes.
Model.find({ 'name.last': 'wang' })
Copy the code
Multi-table union query
Mongoose doesn’t actually have a method for multi-table union queries, but we can do it with multiple queries. Query post: schema.js with user name and Post content
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name : { type: String, unique: true },
posts : [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});
var User = mongoose.model('User', UserSchema);
var PostSchema = new Schema({
poster : { type: Schema.Types.ObjectId, ref: 'User' },
comments : [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
title : String,
content : String
});
var Post = mongoose.model('Post', PostSchema);
Copy the code
User.find({name: name}, function (err, users) {
Post.find({poster: {$in: users}, content: content}, function (err, posts) {
console.log(posts)
})
})
Copy the code
conclusion
These are basically the contents of the documents THAT I often refer to in the last week. While filing, I also learned them. I killed two birds with one stone. However, after finishing the sorting, I feel that the catalogue is not clear enough, and it is still a bit messy. I still need to improve it in the future. At present, I have tried my best. Thank you for watching