2

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/ })
2
  • It looks like you're using mongoid. This is a wrapper around the MongoDB ruby driver and outputs its own queries as it sees fit. Do you have any way to check what query mongoid is actually running? Is it the same one that you ran? Commented May 23, 2011 at 18:40
  • So I believe this is actually a problem with how Mongoid handles embedded Models, if I pull the Messages Models into a referenced model this query works fine. Commented May 23, 2011 at 19:25

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This would also return the User model not the messages model
this correct, but as your model message is embedded inside the model there is simply no way to get the direct message with mongodb, that's not how the embedded documents works... see edit to get that.
if you really want a collection of messages from all users, then you need to not embed messages inside user and reference it rather.
1

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/)

1 Comment

The problem with that is I need to be returned the Message record, not the User record

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.