【问题标题】:Sort the users in MongoDB对 MongoDB 中的用户进行排序
【发布时间】:2021-05-23 03:46:40
【问题描述】:

这是我下面的代码,请告诉我如何在 MongoDb 中按字母顺序对用户进行排序!

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
 
    email: {
        type: String,
        required: true,
        unique: true
    }, 

    password: {
        type: String,
        required: true
    },

    avatar: {
        type: String
    },

    date: {
        type: Date,
        default: Date.now
    }

}, {
    collection: 'users'
});

module.exports = User = mongoose.model('user', UserSchema);

【问题讨论】:

  • 也许db.User.sort( { name: 1 } ) ?

标签: javascript node.js reactjs mongodb


【解决方案1】:

您可以创建支持在 MongoDB 中高效执行查询的索引,减少查询时间。 你可以试试:

UserSchema.index({ name: 1 })

使用此代码,MongoDB 将创建一个name 索引,MongoDB 将按升序对其进行排序。 Read more about indexes in Mongoose 还有MongoDB

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多