1

The query returns two documents:

db.testData.find({x:5}); { "_id" : ObjectId("529680a82ac8f8a788401688"), "x" : 5, "y" : 20, "z" : "hi" } { "_id" : ObjectId("529690982ac8f8a78840169e"), "x" : 5, "y" : 5, "z" : "address" }

How to specify the condition x=y to return the last document?

Philipp
  • 67,764
  • 9
  • 118
  • 153
Hama
  • 13
  • 2

1 Answers1

2

You have to use $where (which is slow and does not use indexes)

Your query will look like this:

db.testData.find({
   x: 5,
   $where: "this.x == this.y"
});

Thinking for a second and looking at your query. If you know that x = 5, you can do this :-)

db.testData.find({x: 5, y : 5});
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • db.testData.find({ $where: "this.x == this.y" }); will give the right answer. – Hama Nov 28 '13 at 05:14
  • The solution from the duplicate which uses the aggregation framework is likely a much better solution than using $where. – Philipp Nov 28 '13 at 09:32
  • Wow, 2 downvotes! This is amazing. This solution can use index on field x = 5, and then it will iterate through all the fields with where. It is easy to write and easy to understand. Solution which is marked as a duplicate is definitely much harder to understand. – Salvador Dali Nov 28 '13 at 22:59