Avatar Edgar González

  • Random
  • Archive
  • RSS

MongoDB how to compare two IDs fields on same document

To compare two fields on same document in MongoDB you can use a $where (just be aware it will be fairly slow, has to execute Javascript code on every record) :

db.my_collection.find( "this.fieldA > this.fieldB" } );

(check this thread on StackOverflow)

In my case I want to find all the documents where a field id_A is equal to field id_B, so I tried this:

db.my_collection.find( "this.id_A == this.id_B" } );

but this not works because you can’t overload == in javascript, so the way to do is:

db.my_collection.find( "this.id_A.equals(this.id_B)" } );

And from ruby with MongoID you use:

MyCollection.where("$where" => "this.id_A.equals(this.id_B)")
    • #mongodb
    • #id
    • #field
    • #ruby
    • #mongoid
  • 10 months ago
  • 6
  • Comments
  • Permalink
  • Share
    Tweet

6 Notes/ Hide

  1. determinesek6 liked this
  2. promontoryop3 liked this
  3. nilamkumarpatel liked this
  4. 3k38leo liked this
  5. edgar posted this

Recent comments

Blog comments powered by Disqus
← Previous • Next →

Portrait/Logo

About

When I'm not spending time with Jessica and my kids, I build web applications. Rails developer, believer of Agile Development and Lean startups. NoSQL enthusiast.
CTO and Lord of the API at Piictu

Me, Elsewhere

  • @edgar on Twitter
  • Facebook Profile
  • edgargonzaleznetve on Youtube
  • egg on Flickr
  • edgar on Foursquare
  • My Skype Info
  • Linkedin Profile
  • edgar on github

Twitter

loading tweets…

  • RSS
  • Random
  • Archive
  • Mobile

Effector Theme by Carlo Franco.

Powered by Tumblr