2014-03-13 58 views
0

如果我有收集了一些文件,這些文件的格式如下:如何比較數學表達式中蒙戈

{ 
    "_id" : ObjectId("53202e1d78166396592cf805"), 
    "a" : 4, 
    "b" : 2, 
    "c" : 4, 
    "d" : 3 
} 

如何選擇與此條件的文件:

db.stat.find({」一個」 + 'b'> 'C' + 'd'})

可能,使用聚合,但隨後什麼條件在節 「macth」:

db.stat.aggregate([ 
{$project : { 
     _id : '$_id', 
     'ab' : { '$add' : [ '$a', '$b' ] }, 
     'cd' : { '$add' : [ '$c', '$d' ] } 
    }}, 
    {$match: {???}} 
]); 

感興趣的解決方案沒有mapReduce和沒有人工方法比較值爲零($subtract:["$ab", "$cd"] > 0)。

+0

在你的比賽中,你爲什麼不使用http://docs.mongodb.org/manual/reference/operator/aggregation/cmp/來查看它是什麼方式?但是,那幾乎就像減法 – Sammaye

+0

@NeilLunn是啊你的答案在這裏是正確的,不知道爲什麼我寫了我所做的 – Sammaye

回答

2

那麼就不會有$比賽前一個步驟:

db.stat.aggregate([ 
    { "$project" : { 
     "ab": { "$add" : [ "$a", "$b" ] }, 
     "cd": { '$add' : [ "$c", "$d" ] } 
    }}, 
    { "$project": { 
     "matched": {"$gt": [ "$ab", "$cd" ] } 
    }}, 
    { "$match": { "matched": true } } 
]) 

甚至更​​好:

db.stat.aggregate([ 
    { "$project": { 
     "matched": { "$gt": [ 
      { "$add" : [ "$a", "$b" ] }, 
      { "$add" : [ "$c", "$d" ] } 
     ]} 
    }}, 
    { "$match": { "matched": true } } 
]) 

對於保持原始文檔see here的概述。

當然,總有這樣,還有「不漂亮」的形式:

db.stats.find(function() { 
    return ((this.a + this.b) > (this.c + this.d)); 
}) 

但是,這是一個快捷方式$where操作形式,這會導致您無法使用索引來進行選擇的能力。

所以希望你可以通過初始$匹配選擇你想要測試的文檔,因此聚合方式更好,因爲最初的$ match可以使用索引。