0

How do I do a MongoDB find comparing two attribute of the same document?

Like, if I have the collection "test", with this structure:

{a : 3, b : 4}
{a : 5, b : 5}
{a : 6, b : 6}

and I want to find all documents where the attribute 'a' is different than the attribute 'b', which would be the entry

{a : 3, b : 4}

.

I thought this could be accomplised by:

db.test.find({a : { $ne : b}})

but it didn't work. It gives me

Fri Aug  1 13:54:47 ReferenceError: b is not defined (shell):1
Cindy Langdon
  • 611
  • 6
  • 12

1 Answers1

0

If this is an ad-hoc query and you don't want to keep track of different attributes (as mentioned in the entry posted by Marc B., then you can simply go with:

db.test.find("this.a != this.b");

This is going to be slow, depending on how many entries you have.

Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64
  • this is wrong - you are sending a string as query which is basically a noop. – Asya Kamsky Aug 01 '14 at 23:04
  • @AsyaKamsky : Just tested it with my toy database and the entries proposed in here, db.test.find("this.a != this.b"); returns {a : 3, b : 4} and db.test.find("this.a == this.b"); returns {a : 5, b : 5} {a : 6, b : 6}. I am using MongoDB shell version: 2.0.4 – Alexandre Santos Aug 01 '14 at 23:22
  • Okay I see - you are using a shortcut which won't work from any driver/application code - this is just sending a $where clause to the back end (you can see it in the logs: "query test.test query: { $where: "this.a==this.b" }"), making the answer a duplicate of http://stackoverflow.com/questions/6399426/mongodb-find-by-comparing-field-values Aggregation is a better way to do it, as that does not involve JS. Btw, unrelated: 2.0.4 is *really* old. – Asya Kamsky Aug 02 '14 at 00:45
  • 1
    btw, this also won't work correctly for NumberLong, NumberInt and other data types that are objects... – Asya Kamsky Aug 02 '14 at 00:47