Mongoose 是 Node.js 中一款流行的 MongoDB ODM(Object Data Mapping) 库,它提供了丰富的API以简化开发者对 MongoDB 数据库的数据操作。
在使用 Mongoose 进行数据库操作时,查询语法是最基础的部分,能够熟练掌握 Mongoose 的查询语法,可以极大地提升开发效率。在本文中,我们将详细讨论 Mongoose 的基本查询语法。
查找数据
使用 Mongoose 查询数据非常简单,我们只需要调用基本 API find() 或者 findOne() 方法。它们的使用方法如下所示:
// www.javascriptcn.com code example
// 找到所有数据
Model.find({}, function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})
// 找到一条数据
Model.findOne({ name: 'jim' }, function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})通过这两个方法,我们可以轻松地查询出所有满足条件的数据。
比较运算符
在查询数据时,我们经常需要使用比较运算符,比较运算符有 $lt、$lte、$gt、$gte、$ne、$in,这几个都是常用的比较运算符。
// www.javascriptcn.com code example
// 查询年龄小于 18 岁的人
Model.find({ age: { $lt: 18 } }, function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})
// 查询年龄大于等于 18 岁的人
Model.find({ age: { $gte: 18 } }, function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})
// 查询名字不为 “jim”的人
Model.find({ name: { $ne: 'jim' } }, function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})
// 查询名字为 “jim” 或者 “lily” 的人
Model.find({ name: { $in: ['jim', 'lily'] } }, function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})逻辑运算符
在查询数据时,我们也需要使用逻辑运算符来组合多个条件。常用的逻辑运算符有 $or、$and、$nor,它们的使用方法如下:
// www.javascriptcn.com code example
// or查询
Model.find({ $or: [{ name: 'jim' }, { age: 20 }] })
.exec(function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})
// and查询
Model.find({ $and: [{ name: 'jim' }, { age: 18 }] })
.exec(function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})
// nor查询
Model.find({
$nor: [{ name: 'jim' }, { name: 'lily' }],
})
.exec(function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})正则匹配
在查询中我们还应该学会正则匹配的用法,通过使用 $regex 运算符,我们可以实现对数据进行模糊查询。
// 查询名字以 ‘j’ 开头的人
Model.find({ name: { $regex: /^j/ } }).exec(function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})返回指定字段
有时候我们并不需要返回所有字段的数据,这时候就需要使用 select() 方法。
// www.javascriptcn.com code example
// 只查询名字和年龄
Model.find({})
.select('name age')
.exec(function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})排序
我们也可以通过 sort() 方法进行排序。默认是升序排列,如果需要降序,需要在后面加上 -。
// www.javascriptcn.com code example
// 以年龄为依据升序排序
Model.find({}).sort('age').exec(function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})
// 以年龄为依据降序排序
Model.find({}).sort('-age').exec(function(error, docs) {
if (error) {
console.log(error)
} else {
console.log(docs)
}
})结束语
Mongoose 提供了很多丰富的查询语法以帮助我们更加高效的进行数据操作。本文介绍了 Mongoose 最常用的查询方法,希望能为读者提供指导和帮助。当然,Mongoose 的查询语法在实际的开发中一定是不可避免的,我们还可以通过翻阅官方文档 API 了解更多高级查询用法。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d64242a941bf7134bf4611