1. 表长度 count()/countDocuments()/countDocuments()
count()/countDocuments()/countDocuments()
在高版本的mongoose中,count()不建议使用
db.user.count({}) db.user.find({}).count()
AI 代码解读
2.排序 sort()
sort函数可以将查询结果数据进行排序操作;
该函数的参数是一个或多个键/值对,键代表要排序的键名,值代表排序的方向,1是升序,-1是降序;
同时,也可以省略键值
//创建时间倒序排列 db.user.find().sort({"create_time":-1}) //按年龄升序,创建时间倒序排列 db.user.find().sort({"age":1,"create_time":-1})
AI 代码解读
3.skip() 跳过多少条数据
skip()函数为跳过多少条数据,一般和limit()同用,取值为数字
//按create_time倒序排序,跳过两条数据 db.user.find().skip(2).sort({"create_time":-1})
AI 代码解读
4. limit() 展示多少条数据
limit()函数为展示多少条数据,,取值为数字
//按create_time倒序排序,跳过两条数据,并展示两条数据 db.user.find().skip(2).limit(3).sort({"create_time":-1})
AI 代码解读
5. distinct()字段去重
Parameters
- field «String» 必填 需要去重的字段
- [conditions] «Object» optional 选填 筛选条件
- [callback] «Function» 选填,一般不用
distinct()可以获取某个字段的所有取值,返回值为数组
db.user.distinct("age") db.user.distinct("age",{"vip":true})
AI 代码解读
6.populate() 关联字段
注意⚠️:
A.此方法一般在可视化工具上无法使用,在代码中可以使用
B.创建 Model 的时候,可给该 Model 中关联存储其它集合 _id 的字段设置 ref 选项。ref 选项告诉 Mongoose 在使用 populate() 填充的时候使用哪个 Model。
在创建文档时,保存 refs 字段与保存普通属性一样,把 _id 的值赋给它就好了
例如:
//organ const Organ = new Schema({ name: { type: String, index: true }, create_time: { type: Date, default: () => new Date(), } });
AI 代码解读
//user const User = new Schema({ name: { type: String, index: true, default:null }, age: { type: Number, default: 0 }, register_time: { type: Date, default: Date.now() }, remark: { type: String, default:null }, vip: { type: Boolean, default: false, }, address: { type: String, default:null, }, organ_id: { type: mongoose.Types.ObjectId, default: "", } });
AI 代码解读
populate({ objParam })
objParam:
- path:需要 populate 的字段。
- populate:多级填充。
- select:从 populate 的文档中选择返回的字段。
- model:用于 populate 的关联 model。如果没有指定,populate 将根据 schema 中定义的 ref 字段中的名称查找 model。可指定跨数据库的 model。
- match:populate 查询的条件。
- options:populate 查询的选项。
- sort:排序。
- limit:限制数量
db.user.findOne({name:"Jom"}) .populate({ path: 'organ_id', model:"Organ", select: "name" }
AI 代码解读