Mongoose Schemas索引

Mongoose Schemas索引

Mongoose 是用于node.js环境的MongoDB对象建模和处理工具。当创建一个文档时, Mongoose 会自动使用 _id 属性为所有的模型建立索引 . 我们可以使用Mongoose来定义模式中的路径级别索引。对于模式中定义的每个索引,Mongoose在应用程序首次启动时会自动运行 createIndex 以创建索引。

创建node应用程序并安装Mongoose:

步骤1: 使用以下命令创建一个node应用程序:

mkdir folder_name
cd folder_name
npm init -y
JavaScript

步骤2: 使用以下命令安装所需模块:

npm install mongoose
JavaScript

项目结构:

它的结构会像下面这样。

Mongoose Schemas索引

示例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);
    })
JavaScript

运行应用程序的步骤: 从项目的根目录使用以下命令运行应用程序:

node script.js
JavaScript

输出:

Connected Successful
Document inserted
JavaScript

以下是Atlas GUI中的默认索引:

Mongoose Schemas索引

示例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);
    })
JavaScript

运行应用程序的步骤: 从项目的根目录中使用以下命令运行应用程序:

node script2.js
JavaScript

运行应用程序的步骤:从项目的根目录中使用以下命令运行应用程序:

node main.js
JavaScript

输出:

Mongoose Schemas索引

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

Mongoose Schemas索引

参考:

https://mongoosejs.com/docs/guide.html#indexes

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册