Mongoose Document Model.where()函数

Mongoose Document Model.where()函数

Model.where()方法是Mongoose API中用于根据条件从集合中提取文档的方法。我们可以直接在任何模型上使用where()方法,并在where()方法中放置各种关联条件来获取结果。Model.where()返回对象数组。每个对象都包含集合中的文档。

设置Node.js应用程序:

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

npm init

步骤2: 在创建 NodeJS 应用程序之后,使用以下命令安装所需的模块:

npm install mongoose

项目结构: 项目的结构将如下所示:

Mongoose Document Model.where()函数

示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在customerSchema上定义了一个模型,有两个列“name”和“orderCount”。最后,我们在Customer模型上使用where方法,这将根据我们提供的条件给我们一个对象数组。在这个示例中,我们找到“orderCount”值大于10的文档。

  • app.js: 将下面的代码写入app.js文件中:
// 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, orderCount: Number } 
) 
  
// Defining customerSchema model 
const Customer = mongoose.model('Customer', customerSchema); 
  
Customer.where('orderCount').gt(10).then(result => { 
    console.log(result) 
});

运行程序的步骤: 要运行此应用程序,请从项目的根目录执行以下命令:

node app.js

输出:

[
    {
        _id: new ObjectId("6304e7c8c21ca86f5ea6fce4"),
        name: 'Customer3',
        orderCount: 20,
        __v: 0
    }
]

示例2: 在本示例中,我们查找“orderCount”值大于5且小于20的文档。

  • app.js: 在app.js文件中写入以下代码:
// 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, orderCount: Number } 
) 
  
// Defining customerSchema model 
const Customer = mongoose.model('Customer', customerSchema); 
  
Customer.where('orderCount').gt(5).lt(20).then(result => { 
    console.log(result) 
});

运行程序的步骤: 要从项目的根目录运行应用程序,请执行以下命令:

node app.js

输出:

[
    {
        _id: new ObjectId("6304e7c8c21ca86f5ea6fce3"),
        name: 'Customer2',
        orderCount: 10,
        __v: 0
    },
    {
        _id: new ObjectId("6305fa9f63f7ccbdbc0ee95c"),
        name: 'Customer3',
        orderCount: 10,
        __v: 0
    },
    {
        _id: new ObjectId("6305fa9f63f7ccbdbc0ee95d"),
        name: 'Customer4',
        orderCount: 10,
        __v: 0
    }
]

参考: https://mongoosejs.com/docs/api/model.html#model_Model-where

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程