mongoDB==根据条件来查询文档

    技术2022-07-29  79

    //插入数据库模块

    const mongoose = require('mongoose');

     

    //连接数据库

    mongoose.connect('mongodb://localhost/playground', { useNewUrlParse: true })

        .then(result => {

            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);

     

    //查询用户集合中的所有文档

    // User.find().then(result => console.log(result));

     

    //通过_id字段查找文档

    // User.findOne({ _id: '5c09f1e5aeb04b22f8460965' }).then(result => {    console.log(result);})

     

    //查找大于15,小于50的文档

    //  User.find({ age: { $gt: 15, $lt: 50 } }).then(result => {   console.log(result);}) 

     

    //查找包含足球的文档

    // User.find({ hobbies: { $in: ['足球'] } }).then(result => { console.log(result) })

     

    //选择要查询的字段,如果不需要查询_id,在前面加个-

    //  User.find().select('name email').then(result => {    console.log(result);});

     

    //根据年龄字段进行升序排列

    // User.find().sort('age').then(result => console.log(result));

     

    //根据年龄字段进行降序排列

    // User.find().sort('-age').then(result => console.log(result));

     

    //skip跳过多少条数据 limit限制查询数量

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

    Processed: 0.012, SQL: 9