22

I have some trouble with mongoid:

  test "Test candidate" do
    User.create(:id => 1, :sex => User::Male, :country => 1, :city => 1)
    User.create(:id => 2, :sex => User::Female, :country => 1, :city => 1)
    User.create(:id => 3, :sex => User::Female, :country => 1, :city => 1)

    user = User.not_in(:id => [2]).second
    assert_not_equal(user.id, 2)
  end

Test failed. I've tried to use where(:id => {'$nid' => [2]}), but it have same effect.

What is wrong? How to use "not in" condition with mongoid?

PS, "second" is ok, with "first" test passed, because id=1

Community
  • 1
  • 1
Mark Pegasov
  • 5,109
  • 9
  • 26
  • 30

2 Answers2

46

Try this query:

user = User.not_in(:_id => [2]).second

In MongoDB primary key has name _id. Mongoid tries to be friendly and partially hides this fact from the developer by aliasing it to id in the object model. But when you do queries, it cannot tell if you want primary key _id or some completely ordinary field id.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
16
user = User.where(:id.nin => [2,3,4,5])

This is as per mongoid official doc : http://mongoid.org/en/origin/docs/selection.html

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Pushp Raj Saurabh
  • 1,174
  • 12
  • 16