當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Mongoose Query.prototype.gte()用法及代碼示例

Mongoose 是 MongoDB 的對象數據建模 (ODM) 庫。它定義了一個強類型模式,具有默認值和模式驗證,稍後將其映射到 MongoDB 文檔。

此方法用於選擇字段值大於或等於(>=)給定值的文檔。

用法:

Modal.find().where([path]).gte(val)

參數:

  • path:它是一個表示字段名稱的字符串,這是一個must-have參數。
  • val:這是我們想要查找該路徑的文檔的數字,大於該數字。

Mongoose 模塊的安裝:

第 1 步:您可以訪問安裝 mongoose 模塊的鏈接。您可以使用此命令安裝此軟件包。

npm install mongoose

步驟2:安裝mongoose模塊後,您可以使用命令在命令提示符中檢查您的mongoose版本。

npm version mongoose

步驟3:之後,您可以創建一個文件夾並添加一個文件,例如index.js,要運行該文件,您需要運行以下命令。

node index.js

項目結構: 項目結構將如下所示:

示例 1:我們有一些客戶數據,其中包含他們的姓名、興趣和訂單計數。在此示例中,我們要查找訂單數大於或等於 6 的客戶。

Javascript


// Require mongoose module
const mongoose = require('mongoose');
// Set Up the Database connection
mongoose.connect(
    'mongodb://localhost:27017/geeksforgeeks', {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
// Defining customerSchema schema
const customerSchema = new mongoose.Schema({ 
    name: String, 
    interest: Array, 
    orderCount: Number 
})
// Defining customerSchema model
const Customer = mongoose.model(
    'Customer', customerSchema);
// Find the number of customers whose
// orderCount are greater than 6
Customer.find().where("orderCount")
.gte(6).then((res) => {
    console.log(res)
});

運行應用程序的步驟:

步驟1:下麵是函數執行之前數據庫中的示例數據,您可以使用任何GUI工具或終端來查看數據庫,就像我們使用MongoDB指南針GUI工具一樣,如下所示:

步驟 2:使用以下命令運行 index.js 文件:

node index.js

示例 2:在此示例中,我們在此方法中沒有傳遞任何值作為值。我們看到它返回了該字段的所有文檔。

Javascript


// Require mongoose module
const mongoose = require('mongoose');
// Set Up the Database connection
mongoose.connect(
    'mongodb://localhost:27017/geeksforgeeks', {
    useNewUrlParser: true,
    useUnifiedTopology: true
})
// Defining customerSchema schema
const customerSchema = new mongoose.Schema({ 
    name: String, 
    interest: Array, 
    orderCount: Number 
})
// Defining customerSchema model
const Customer = mongoose.model(
    'Customer', customerSchema);
Customer.find().where("orderCount")
.gte().then((res) => {
    console.log(res)
});

運行應用程序的步驟:使用以下命令運行index.js 文件:

node index.js

參考: https://mongoosejs.com/docs/api/query.html#query_Query-gte



相關用法


注:本文由純淨天空篩選整理自devi_johns大神的英文原創作品 Mongoose Query.prototype.gte() API。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。