mongodb

Mongodb query with fields in the same documents


I have the following json:

{
  "a1": {"a": "b"},
  "a2": {"a": "c"}
}

How can I request all documents where a1 and a2 are not equal in the same document?


Solution

  • You could use $where:

    db.myCollection.find( { $where: "this.a1.a != this.a2.a" } )
    

    However, be aware that this won't be very fast, because it will have to spin up the JavaScript engine and iterate each and every document and check the condition for each.

    If you need to do this query for large collections, or very often, it's best to introduce a denormalized flag, like areEqual. Still, such low-selectivity fields don't yield good index performance, because he candidate set is still large.