在MongoDB中查询数据

在MongoDB中查询数据

//引入moogodb模块
const mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://localhost/playground', {
      useNewUrlParser: true, useUnifiedTopology: true })
    //连接成功
    .then(() => {
     
        console.log('数据库连接成功');
    })
    //连接失败
    .catch(err => {
     
        console.log(err, '数据库连接失败');
    });
    //创建集合规则
const userSchema = new mongoose.Schema({
     
    name: String,
    age: Number,
    email: String,
    password: String,
    hobbies: [String]
})
//使用集合规则  创建集合
const User = mongoose.model('User', userSchema);

//查询用户中的所有文档  find的返回值是一个数组
// User.find().then(result => {
     
//     console.log(result);
// })

//查询id为他的文档
// User.find({ _id: '5c09f1e5aeb04b22f8460965' }).then(result => {
     
//     console.log(result);
// })


//findOne返回一条文档  默认返回当前第一条文档  findOne的返回值是一个对象
// User.findOne({ name: '李四' }).then(result => {
     
//     console.log(result);
// })


//匹配 大于 小于   查询用户集合中  年龄大于20且小于50的情况
// User.find({ age: { $gt: 20, $lt: 50 } }).then(result => {
     
//     console.log(result);
// })


//匹配包含
// User.find({ hobbies: { $in: ['敲代码'] } }).then(result => {
     
//     console.log(result);
// })

//选择要查询的字段  在属性名的前面加上-就是不查询它
// User.find().select('name email -_id').then(result => {
     
//     console.log(result);
// })

//根据年龄字段进行升序排序
// User.find().sort('age').then(result => {
     
//     console.log(result);
// })
//根据年龄字段进行降序排序  加上-号就是降序排序
// User.find().sort('-age').then(result => {
     
//     console.log(result);
// })

User.find().skip(2).limit(3).then(result => {
     
    console.log(result);
})

你可能感兴趣的:(mongodb,mongodb)