Meteor数据库mongodb查询

当我们进行数据查询的时候,默认数据发布的时候是不带条件过滤,可能将全部的数据发布到客户端,这是无法想象的,因此我们采用几种措施来提高查询效率:

使用正则查询

没有查询条件的代码

// location: /server/app.js

Meteor.publish('getEntries', function(searchText) {
  return Entries.find({}, {sort: {name: 1}, limit:20});
});

改进后:

Meteor.publish('getEntries', function(searchText) {
  // second paramter 'i' indicates that we want our regular expression to be case-insensitive.
  var filter = new RegExp(searchText, 'i');
  return Entries.find({name: filter}, {sort: {name: 1}, limit:20});
});

上面的查询方式可能是inefficient,最好在使用过程中加上索引,Meteor mongo启动后,使用以下语句添加索引:

db.entries.ensureIndex({name:1})

检索过程使用精确的匹配符和大小写将提高查询效率,eg:

db.entries.find({name: new RegExp("^Tom")}).explain()

忽略大小写将降低查询效率,以下语句可同上面的查询进行对比:

db.entries.find({name: new RegExp("^Tom", "i")}).explain()

使用全文检索查询

全文检索在mongodb2.6里面成为默认支持的功能,搜索文档的时候将变得更加敏捷。
使用全文检索前需添加text类型的index。

db.entries.ensureIndex({name: "text"});

查询:

Entries.find({$text: {$search: searchText}});
Entries.find({$text: {$search: searchText}, age: {$gt: 25}});

当使用复合条件查询时,可修改索引为

db.entries.ensureIndex({name: "text", age: 1});
Entries.find({$text: {$search: searchText}, age: {$gt: 25}});

When to Use Regular Expression Search

Here are some of the places you can use Regular Expression Search:

If you need real-time searching capabilities
If your dataset size is not more than few thousand documents
If you need partial word matching
If you need to save disk space
When to Use Full Text Search

If your dataset is big, and you need high-performance search results
If you can afford more disk space
If you need language-specific search requirements
If you don’t need real-time search (actually, real-time updates)
It is very important not to create publications contain Full Text Search–related queries. Since it does not support oplog tailing, Meteor will poll the db for changes. This could be very costly for both Meteor and MongoDB.

So if you’re going with Full Text Search, always get data from a method rather than by using a publication.
If you’re going to use Full Text Search, you need to allocate enough space and memory for your MongoDB instance. You can learn about this in detail here.

Other Options

It’s clear that both of the above solutions are very limited in functionality and have some issues. That’s why MongoDB is not a good solution for searching. Therefore, you may need to use some other solutions. Here are two of the best:

Elastic Search—One of best open source search solutions
Algolia—A cloud-based solution
In an upcoming lesson, we’ll talk about how to use Elastic Search with Meteor. You may also have had some good search experiences. If so, please share those with us in the comments section.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值