aressidi
aressidi

Reputation: 680

Mongoid - two query conditions to both be met in an embedded doc?

I have two models

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  field :username
   embeds_many :user_tags
end

class UserTag
  include Mongoid::Document
  field :name
  field :like_count, :type => Integer, :default => 0
  embedded_in :user
end

I want to query all the users that have the user_tag named "nyc" and where the user_tag "nyc" has a like_count > 10. I've tried the following:

users = User.where('user_tags.name' => "nyc").and('user_tags.like_count' => {'$gte' => 10 })

Logically this does what it's supposed to do, but not what I need it to do. It returns users that have the user_tag "nyc" and have any user_tag with a like_count >= 10. I need users that have the user_tag "nyc" and where the user_tag "nyc"'s like_count is >= 10.

How do I do that? I'm running mongoid 4.0.2.

Upvotes: 1

Views: 502

Answers (3)

dimakura
dimakura

Reputation: 7655

Actually your query is not correct for the purpose you are trying to achieve. It translates to the following MongoDB query:

db.users.find({'user_tags.name': 'nyc' }, {'user_tags.like_count': {$gte: 10}})

It means that MongoDB will find all documents with both criteria. Mongoid is returning you the same data, as MongoDB.

What you need instead is the following MongoDB query:

db.users.find({ user_tags: {
  $elemMatch: {
    name: 'nyc',
    like_count: { $gte: 10  }
  }
}})

With Mongoid you can write:

User.where(user_tags: {
  '$elemMatch' => {
    name: 'nyc',
    like_count: { '$gte' => 10 }
  }
}).count

Upvotes: 1

Rajarshi Das
Rajarshi Das

Reputation: 12340

You can try this

users = User.where('user_tags.name' => "nyc").where('user_tags.like_count' => {'$gte' => 10 }).all

or

users = User.where('user_tags.name' => "nyc", 'user_tags.like_count' => {'$gte' => 10 }).all

Upvotes: 0

Mr.D
Mr.D

Reputation: 7893

Maybe you should write something like this:

users = User.where('user_tags.name' => "nyc", 'user_tags.like_count' => {'$gte' => 10 })

Mongoid will try to find Documents which satisfies both conditions.

Upvotes: 0

Related Questions