MongoDB comparison operators with null

别说谁变了你拦得住时间么 提交于 2019-12-01 03:14:30
cyfur01

Nitty-Gritty Details

Reading through the latest Mongo source, there's basically 2 cases when doing comparisons involving null:

  1. If the canonical types of the BSON elements being compared are different, only equality comparisons (==, >=, <=) of null & undefined will return true; otherwise any comparison with null will return false.
    Note: No other BSON type has the same canonical type as null.
  2. If the canonical types are the same (i.e., both elements are null), then compareElementValues is called. For null, this just returns the difference between the canonical type of both BSON elements and then carries out the requested comparison against 0.
    For example, null > null would translate into (5-5) > 0 --> False because the canonical type of null is 5.
    Similarly, null < null would translate into (5-5) < 0 --> False.

This means null can only ever be equal to null or undefined. Any other comparison involving null will always return false.

Is this a Bug?

Updated Answer:

The documentation for the comparison operators ($gt, $lt) references the documentation which you originally linked, which implies that the comparison operators should work with null. Furthermore, query sorting (i.e., db.find().sort()) does accurately follow the documented Comparison/Sort behavior.

This is, at the very least, inconsistent. I think it would be worth submitting a bug report to MongoDB's JIRA site.


Original Answer:

I don't think this behavior is a bug.

The general consensus for Javascript is that undefined means unassigned while null means assigned but otherwise undefined. Value comparisons against undefined, aside from equality, don't make sense, at least in a mathematical sense.

Given that BSON draws heavily from JavaScript, this applies to MongoDB too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!