gpt4 book ai didi

ruby - 使用 Ruby 驱动程序的 MongoDB 组

转载 作者:可可西里 更新时间:2023-11-01 09:14:40 26 4
gpt4 key购买 nike

我正在尝试返回一个包含用于描述博文的计数的年/月组合列表。这个想法是它们将像这样显示:

  • 2010 年 1 月(1 个帖子)
  • 2009 年 12 月(2 个职位)
  • ...

我已经设法使用 MongoDB JS shell 让它工作,并且它以有用的格式返回结果:

db.posts.group({ 
keyf: function(x){
return {
month: x.datetime.getMonth(),
year:x.datetime.getFullYear()
};
},
reduce: function(x,y){ y.count++ },
initial:{count:0}
})

结果:

[ { "month" : 0, "year" : 2010, "count" : 3 },
{ "month" : 0, "year" : 1970, "count" : 1 } ]

这太棒了,正是我所追求的。然而,试图将其转换为适合 ruby​​ 驱动程序的代码,我无法让它工作。我查看了文档,根据我的理解,以下内容应该会产生相同的结果(我使用的是 MongoMapper,因此是 Post.collection):

@archive = Post.collection.group(
"function(x) { return { month: x.datetime.getMonth(), year:x.datetime.getFullYear() }; }",
nil, { :count => 0 }, 'function(x,y){y.count++}', true)

我没有返回大量有用的数据,而是得到了这样一团糟:

{
"function(x) { return { month: x.datetime.getMonth(), year:x.datetime.getFullYear() }; }" => nil,
"count" => 4.0
}

它似乎完全违背了它自己的文档(以及我对源代码的理解!),或者我在这里遗漏了一些基本的东西。我几乎要拔头发了,感激地接受任何帮助。

最佳答案

这是非常奇怪的行为。我只是在本地运行你的代码,一切正常。您能否确认您使用的是 0.18.2 版驱动程序?如果是这样,请确保这是唯一安装的版本(就像完整性检查一样)。

我不认为它应该有任何区别,但我没有从 MongoMapper 运行#group——我是单独使用 gem。你也可以试试看。这是我运行的代码:

require 'rubygems'
require 'mongo'

d = Mongo::Connection.new.db('blog')
c = d['post']

p c.group("function(x) { return { month: x.date.getMonth(), year:x.date.getFullYear() }; }",
nil,
{ :count => 0 },
"function(x,y){y.count++}",
true)

关于ruby - 使用 Ruby 驱动程序的 MongoDB 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2127374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com