Is it possible to switch the dividend and the divisor of MongoDB's $mod query operator?

孤街浪徒 提交于 2019-12-24 05:48:07

问题


MongoDB's $mod query operator provides a way to select documents where the value V of a field divided by a divisor D has the specified remainder R. So it selects documents where V mod D equals R.

I need to switch the dividend and the divisor of the modulo operation. In other words, I need to select documents where a provided dividend D divided by the value V of a field has the specified remainder R. So I need to select documents where D mod V equals R.

Is it possible to switch the dividend and the divisor of MongoDB's $mod query operator? If not, is it possible to pass the query a custom function which would take care of this?


回答1:


A regular .find query with the $mod operator will not work here, but still, you can do this using the aggregation framework and the $redact operator and the $mod arithmetic aggregation operator.

Suppose we have the following documents in our collection:

{ "_id" : ObjectId("573f624b4c01ce47a183a632"), "a" : 4 },
{ "_id" : ObjectId("573f63494c01ce47a183a634"), "a" : 12 },
{ "_id" : ObjectId("573f63504c01ce47a183a635"), "a" : 6 },
{ "_id" : ObjectId("573f63504c01ce47a183a636"), "a" : 24 }

The following query return all those documents where 60 modulo the value of the field a equals 0.

db.collection.aggregate([
    { "$redact": { 
        "$cond": [ 
            { "$eq": [ {"$mod": [ 60, "$a" ] }, 0 ] }, 
            "$$KEEP", 
            "$$PRUNE"
        ]
    }}
])

which produces:

{ "_id" : ObjectId("573f624b4c01ce47a183a632"), "a" : 4 }
{ "_id" : ObjectId("573f63494c01ce47a183a634"), "a" : 12 }
{ "_id" : ObjectId("573f63504c01ce47a183a635"), "a" : 6 }

Another probably less efficient way to do it, is to use the $where operator.

db.collection.find("60 % this.a === 0")


来源:https://stackoverflow.com/questions/37353521/is-it-possible-to-switch-the-dividend-and-the-divisor-of-mongodbs-mod-query-op

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