Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying an array field that contains hashes in mongoid

I have a model like this

class User
  include Mongoid::Document
  field :c, as: :categories, type: Array
end

and I am storing information on it like this:

a = UserCheckin.new
a.c = [{id: rand(1000), name: 'a'}, {id: rand(1000), name: 'b'}, {id: rand(1000), name: 'c'}]
a.save

I do not know if I am misusing the array type by storing hashes on it, but the thing is that mongodb does not complain about it.

How do I query something like Users where category name is 'a' or category id is higher than 2?

Thanks in advance,

like image 534
chopi321 Avatar asked Mar 14 '13 12:03

chopi321


People also ask

How do I query an array field in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do I match an array in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

How do I remove an element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do I use $in in MongoDB?

Use the $in Operator to Match Values This query selects all documents in the inventory collection where the value of the quantity field is either 5 or 15. Although you can write this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.


1 Answers

I've seem to have find the answer... For anyone left, I will post it here.

User.where(c: {'$elemMatch' => {name: 'a'}})

It will return all the Users, whose categories array has one or more element with a name of 'a'.

like image 160
chopi321 Avatar answered Oct 23 '22 22:10

chopi321