trobrock
trobrock

Reputation: 47347

Mongoid regex for an element in Array

I have two models, a User and an embedded model Message

class User
  include Mongoid::Document
  embeds_many :messages
end

class Message
  include Mongoid::Document

  field :keywords, :type => Array
end

I am trying to do something like:

u = User.last
u.messages.where(:keywords => /sometext/).first

But this returns nothing, the regex seems to work fine if the field is not of type Array and is a String. How can I do something like this with Mongoid?

I should also mention this Mongo query works fine:

db.users.find({"messages.keywords" : /index/ })

Upvotes: 2

Views: 3058

Answers (2)

Alex
Alex

Reputation: 4507

If you are dealing with an array, you use "in".

 users = User.where("messages.keywords".in => [/sometext/])

should work if I am not mistaken.

Alex

User.where("messages.keywords".in => [/sometext/]).each do |user|
  message_collection_for_user = user.messages.where("keywords".in => [/sometext/])
end

Now you have your messages and can do whatever, but you can't get a collections of messages for all users it does not work that way.

Upvotes: 2

Ryan McGeary
Ryan McGeary

Reputation: 239914

Your direct Mongo query is finding all user documents that have embedded messages with the specified matching substring. It looks like the intention of your Mongoid query is to find a matching message on an already returned user document. I'm not sure which behavior you're looking for, but if you want to perform the same Mongo-direct query in Mongoid, it would look something like this:

users = User.where("messages.keywords" => /sometext/)

Upvotes: 1

Related Questions