我真正想做的是根据文档的属性值制作用于过滤和字符串匹配文档的索引。
我知道mongodb内置了诸如$text之类的运算符,这些运算符对此类功能非常有帮助。
我不确定在使用猫鼬时如何访问这些运算符,或者是否需要使用任何方法来访问它们。
我想使用猫鼬来定义模式和模型,但需要原生 mongodb 的功能。
这可能吗?
以下是我的观点,如果我遗漏了任何内容或需要修改或解释的内容,请添加:
1. You will still be able to use mongoDB's native functionalities on using Mongoose models.
2. Mongoose is a kind of wrapper on top of native mongoDB-driver.
3. It would be very useful if you want to have schema based collections/data.
4. Additionally it would provide few more features than native mongoDB's driver. You might see few syntax differences between those two.
5. Few examples like `.findByIdAndUpdate()` & `.populate()` are mongoose specific, which has equivalent functionalities available in mongoDB driver/mongoDB as well.
6. In general it's quiet common to define mongoose models and use those over mongoDB's functionality in coding(As in node.js - You would write all of your same DB queries on Mongoose models, queries that you execute in DB).
要点 2 :
Mongoose是一个对象文档建模(ODM(层,位于Node的MongoDB驱动程序之上。如果你来自SQL,它类似于关系数据库的ORM。
要点 3 :
在代码中,如果您使用猫鼬模型来实现写入查询,除非您在模型中定义一个字段 - 即使您在请求中传递它,它不会添加到数据库中。此外,您可以执行多种操作,例如使字段唯一/必需等。这有点让你的mongoDB数据看起来像是基于模式的。如果你的集合数据更像是随机数据(新闻源那种每个文档的字段都不相同并且您无法预测数据的东西(,那么你可能不在乎使用猫鼬。
要点 6 :
假设您使用 mongo shell 或像 mongo compass/robo3T 这样的客户端并执行如下所示的查询:
db.getCollection('yourCollection').find(
{
$text: {
$search: 'employeeName',
$diacriticSensitive: false
},
country: 'usa'
},
{
employee_id: 1,
name: 1
}
).sort({ score: { $meta: 'textScore' } });
你会在猫鼬模型上做同样的事情(因为你的收藏模型已经定义(:
yourCollectionModel.find(
{
$text: {
$search: 'employeeName',
$diacriticSensitive: false
},
country: 'usa'
},
{
employee_id: 1,
name: 1
}
).sort({ score: { $meta: 'textScore' } });
在使用猫鼬时,您会在写入而不是读取时看到更多的关键功能差异,尽管以上所有内容都与性能无关 - 如果您问我,我可以说您可能会看到使用猫鼬的性能提升很多。
参考 : 猫鼬 vs MongoDB 驱动程序