MongoDBRuby中如何嵌入Javascript

52次阅读
没有评论

共计 1615 个字符,预计需要花费 5 分钟才能阅读完成。

自动写代码机器人,免费开通

这篇文章将为大家详细讲解有关 MongoDBRuby 中如何嵌入 Javascript,文章内容质量较高,因此丸趣 TV 小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

MongoDBRuby 中怎样嵌入 Javascript

class Publication

include Mongoid::Document

field :name, :type = String

field :section, :type = String

field :body, :type = String

field :is_published, :type = Boolean

end

class LongerPublication

field :extra_body, :type = String

end

此时系统中已经存在一个 Publication 类和一个 LongerPublication 类。现在需要做一些信息汇总方面的工作,想通过 Publication 类对象的类型与状态得到对其的数量统计信息。另外最好能够按照当前的状态进行具有针对性的统计分析。

一种方法是使用 Mongo 内置的 map-reduce。Mongoid 扩展了该功能,让程序员可以使用 Ruby 程序实现其所需的内联 Javascript 函数 (mapper 和 reducer)。读者可能觉得这种方法并不好,不过似乎这是目前最好的方法了。有很多更复杂的函数将这些 Javascript 函数分别写到不同的文件中,这样做也许更便于测试,但读者如果自行测试整个工作中这项工作的输入 / 输出,就会发现其性能并不好。

MongoDBRuby 中怎样嵌入 Javascript

KLASS = this._type

SECTION = this.section

def self.count_by(type)

map =
function() {
function truthy(value) {
return (value ==true) ?1 :0;
emit(#{type}, {type: #{type}, count:1, published: truthy(this.is_published)})
reduce =
function(key, values) {
var count =0; published =0;
values.forEach(function(doc) {
count += parseInt(doc.count);
published += parseInt(doc.published);
type = doc.type
return {type: type, count: count, published: published}
collection.mapreduce(map, reduce).find()
在进行实验测试时会返回类似如下代码所示的数据; 不过有些读者在实验时也有可能返回 Mongo::Cursor,通过 Mongo::Cursor 可以获取到以下数据。
[{_id = Publication , value = { type = Publication , count = 42.0, published = 29.0}},

{_id = LongerPublication , value = { type = LongerPublication , count = 12.0, published = 10.0}}]

Mongo 与 Mongoid 使我非常喜欢这种信息汇总时的 mapreduce 工作,特别是将 Ruby 与 Javascript 这两种编程语言混合在一起编写,并没有影响到代码的可读性。而如果给定一个关系数据库,用户有可能写出各种各样千奇百怪的 SQL 语句——因为与其他任意语言和 SQL 之间的语法差异相比,Javascript 和 Ruby 之间的语法差异都要小得多。

关于 MongoDBRuby 中如何嵌入 Javascript 就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向 AI 问一下细节

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-04发表,共计1615字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)