文章の目录
一、根据条件查找文档(条件为空则查找所有文档)
通过find
方法
// 查询用户集合中的所有文档
User.find().then(result => console.log(result));
// 通过_id字段查找文档
User.find({
_id: "5c09f267aeb04b22f8460968" }).then(result => console.log(result));
二、根据条件查找一个文档
findOne
方法返回一条文档,默认返回当前集合中的第一条文档
// findOne方法返回一条文档 默认返回当前集合中的第一条文档
User.findOne({
name: "李四" }).then(result => console.log(result));
三、查找大于或者小于的文档
// 查询用户集合中年龄字段大于20并且小于40的文档
User.find({
age: {
$gt: 20, $lt: 40 } }).then(result => console.log(result));
四、查找包含某些数据的文档
// 查询用户集合中hobbies字段值包含足球的文档
User.find({
hobbies: {
$in: ["足球"] } }).then(result => console.log(result));
五、选择要查询的字段
通过select
添加字符串来控制需要查询哪些字段
// 选择要查询的字段
User.find()
.select("name email")
.then(result => console.log(result));
默认显示_id,如果要去掉,需要在要查询的字段后面跟上-_id
// 选择要查询的字段
User.find()
.select("name email -_id")
.then(result => console.log(result));
六、查询结果排序
通过sort方法来排序,默认升序
// 根据年龄字段进行升序排列
User.find()
.sort("age")
.then(result => console.log(result));
如果要降序排序,只需要在根据排序的字段前加-
// 根据年龄字段进行降序排列
User.find()
.sort("-age")
.then(result => console.log(result));
七、查询文档跳过前面几个文档(skip),限制显示多少条结果(limit)
// 查询文档跳过前两条结果 限制显示3条结果
User.find()
.skip(2)
.limit(3)
.then(result => console.log(result));
写在最后
如果你感觉文章不咋地
//(ㄒoㄒ)//
,就在评论处留言,作者继续改进;o_O???
如果你觉得该文章有一点点用处,可以给作者点个赞;\\*^o^*//
如果你想要和作者一起进步,可以微信扫描二维码,关注前端老L;~~~///(^v^)\\\~~~
谢谢各位读者们啦(^_^)∠※
!!!