Mongomapper 对哈希键的查询

发布于 2024-11-29 16:16:00 字数 551 浏览 1 评论 0原文

我有一个一天的模型,每一天都包含一个标签哈希。

class Day
  include MongoMapper::Document

  key :tags, Hash
  ...
end

标签哈希可能看起来像这样 {"a"=>4, "b"=>1, "c"=>1}

我想编写一个查询,可以找到带有标签键的所有日期等于“a”。

Day.where('tags.keys' => "a")

这是行不通的,因为键实际上并不是哈希中的键,我猜我不能只使用键方法。

我真的很想知道是否有办法查询哈希的键,否则我将不得不创建一个数组来存储键并查询它。

tags = {"a"=>4, "b"=>1, "c"=>1, "names" => ["a", "b", "c"]}

Day.where('tags.names' => "a") #This would work find, but is not what I want

I have a model for a Day and each day contains a tag hash.

class Day
  include MongoMapper::Document

  key :tags, Hash
  ...
end

The tags hash might look like this {"a"=>4, "b"=>1, "c"=>1}

I would like to write a query that can find all of the days with a tag key equal to 'a'.

Day.where('tags.keys' => "a")

This doesn't work, since keys is not actually a key in the hash and I'm guessing I can't just use the keys method.

I would really like to know if there is a way to query the keys of a hash, otherwise I will have to create an array to store the keys in and query that.

tags = {"a"=>4, "b"=>1, "c"=>1, "names" => ["a", "b", "c"]}

Day.where('tags.names' => "a") #This would work find, but is not what I want

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

睡美人的小仙女 2024-12-06 16:16:00

我找到了解决办法。

Day.where('tags.a' => {'$exists' => true})

这将返回带有 'a' 键的所有日期。

事实上,我可以为 Day 编写一个方法,如下所示

def self.find_all_by_tag(tag)
  Day.where("tags.#{tag}" => {'$exists' => true}).all
end

然后很容易通过某个标签获取所有日期,如下所示:

Day.find_all_by_tag("a")

I have found a solution.

Day.where('tags.a' => {'$exists' => true})

This will return all days with an 'a' key.

In fact I can write a method for Day like this

def self.find_all_by_tag(tag)
  Day.where("tags.#{tag}" => {'$exists' => true}).all
end

Then it would be easy to get all days by a certain tag like this:

Day.find_all_by_tag("a")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文