Mongoose Schemas索引
Mongoose 是用于node.js环境的MongoDB对象建模和处理工具。当创建一个文档时, Mongoose 会自动使用 _id 属性为所有的模型建立索引 . 我们可以使用Mongoose来定义模式中的路径级别索引。对于模式中定义的每个索引,Mongoose在应用程序首次启动时会自动运行 createIndex 以创建索引。
创建node应用程序并安装Mongoose:
步骤1: 使用以下命令创建一个node应用程序:
mkdir folder_name
cd folder_name
npm init -y
步骤2: 使用以下命令安装所需模块:
npm install mongoose
项目结构:
它的结构会像下面这样。

示例1: 在这个示例中,我们将创建一些文档并查看默认索引,这些索引是由mongoose自动设置的。
// Require the mongoose module
const mongoose = require('mongoose');
// Path to our Database
const url = 'mongodb://localhost:27017/GFG'
// Connecting to database
mongoose.connect(url)
.then((ans) => {
console.log("Connected successfully")
})
.catch((err) => {
console.log("Error in the Connection")
})
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the collection
const collection_structure = new Schema({
name: String,
marks: Number,
})
// Creating collection
const collections = mongoose.model("GFG", collection_structure)
collections.create({
name: `Ragavpp`,
marks: 13,
})
.then((ans) => {
console.log("Document inserted")
})
.catch((err) => {
console.log(err.Message);
})
运行应用程序的步骤: 从项目的根目录使用以下命令运行应用程序:
node script.js
输出:
Connected Successful
Document inserted
以下是Atlas GUI中的默认索引:

示例2: 在这个示例中,我们将使用 mobile_No. 创建索引。
// Require the mongoose module
const mongoose = require('mongoose');
// Path to our cloud DataBase
const url = 'mongodb://localhost:27017/GFG'
// Connecting to database
mongoose.set('strictQuery', false);
mongoose.connect(url)
.then((ans) => {
console.log("Connected Successful")
})
.catch((err) => {
console.log("Error in the Connection")
})
// Calling Schema class
const Schema = mongoose.Schema;
// Creating Structure of the collection
// And making indexes using mobile
const collection_structure = new Schema({
name: {
type: String,
require: true,
},
marks: {
type: Number,
default: 0
},
mobile: {
type: Number,
index: true,
require: true,
}
})
// Creating collection
const collections = mongoose.model("GFG", collection_structure)
collections.create({
name: `Sam Snehil`,
marks: 88,
mobile: 9338948473,
})
.then((ans) => {
console.log("Document inserted")
})
.catch((err) => {
console.log(err);
})
运行应用程序的步骤: 从项目的根目录中使用以下命令运行应用程序:
node script2.js
运行应用程序的步骤:从项目的根目录中使用以下命令运行应用程序:
node main.js
输出:

在Atlas GUI上,我们可以看到以下指标的移动情况:

参考:
https://mongoosejs.com/docs/guide.html#indexes
极客教程