Mongoose Query.prototype.elemMatch() 函数
Mongoose Query API.prototype.elemMatch() 方法 是用于查询对象的Mongoose API的方法。它允许我们匹配包含数组字段的文档,并且该数组列表中至少有一个元素匹配查询表达式或筛选条件。让我们通过一个示例了解 elemMatch() 方法。
语法:
query.elemMatch( path, filter );
参数: 该方法接受两个参数,如下所述:
- path: 用于指定集合中的路径或字段名称。
- filter: 用于指定筛选条件。可以是对象或函数。
返回值: 该方法返回查询对象。
设置 Node.js Mongoose 模块:
步骤1: 使用以下命令创建一个 Node.js 应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
数据库结构: 数据库结构将如下所示,以下数据库存在于MongoDB中。
示例1: 下面的示例展示了Mongoose Connection elemMatch()方法的基本功能。我们正在获取所有marks数组中任意元素大于80的文档。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks";
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
rollNumber: { type: Number, required: true },
marks: []
});
const StudentModel = connectionObject.model('Student', studentSchema);
const query = StudentModel.find()
query.where('marks');
query.elemMatch({ $gte: 80 })
query.exec((error, result) => {
if (error) {
console.log("Error -", error);
} else {
console.log("Result -", result);
}
})
运行程序的步骤: 要运行应用程序,请在项目的根目录下执行以下命令:
node app.js
输出:
Result - [
{
_id: new ObjectId("63c2f65ae00fb130bfb5075b"),
name: 'Student2',
age: 18,
rollNumber: 65,
marks: [ 52, 36, 45, 85, 21 ],
__v: 0
},
{
_id: new ObjectId("63c2f65ae00fb130bfb5075c"),
name: 'Student3',
age: 15,
rollNumber: 36,
marks: [ 85, 69, 42, 32, 16 ],
__v: 0
}
]
示例2: 下面的示例演示了Mongoose连接 elemMatch() 方法的基本功能。我们正在获取marks数组中任何元素大于20且小于50的所有文档。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
// Set Up the Database connection
const URI = "mongodb://localhost:27017/geeksforgeeks";
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const studentSchema = new mongoose.Schema({
name: { type: String, required: true },
age: Number,
rollNumber: { type: Number, required: true },
marks: []
});
const StudentModel = connectionObject.model('Student', studentSchema);
const query = StudentModel.find()
query.elemMatch('marks', { gte: 20,lte: 50 })
query.then(res => {
console.log(res);
}).catch(err => console.log(err));
运行程序的步骤: 要运行该应用程序,请从项目的根目录下执行以下命令:
node app.js
输出:
[
{
_id: new ObjectId("63c2f65ae00fb130bfb5075a"),
name: 'Student1',
age: 25,
rollNumber: 36,
marks: [ 25, 35, 61, 28, 45 ],
__v: 0
},
{
_id: new ObjectId("63c2f65ae00fb130bfb5075b"),
name: 'Student2',
age: 18,
rollNumber: 65,
marks: [ 52, 36, 45, 85, 21 ],
__v: 0
},
{
_id: new ObjectId("63c2f65ae00fb130bfb5075c"),
name: 'Student3',
age: 15,
rollNumber: 36,
marks: [ 85, 69, 42, 32, 16 ],
__v: 0
}
]
参考资料: https://mongoosejs.com/docs/api/query.html#query_Query-elemMatch