如何选择字段总和大于 MongoDB 中的值的位置

ksc*_*ott 6 mongodb nosql mongodb-query

使用 MongoDB,我将如何编写此常规 SQL 语句?

SELECT * FROM table WHERE (field1+field2+field3) > 1
Run Code Online (Sandbox Code Playgroud)

我一直在搞乱 $group、$project、$add 等。我觉得我在围绕解决方案跳舞,但无法弄清楚。

Sal*_*ali 5

最简单的方法是使用$where(我不是说不可能通过聚合来做到这一点)

db.table.find({$where: function() {
   return this.field1 + this.field2 + this.field3 > 1
   // most probably you have to handle additional cases if some of the fields do not exist.
}}
Run Code Online (Sandbox Code Playgroud)

它的优点是简单直观,而缺点是:

要求数据库处理集合中每个文档的 JavaScript 表达式或函数。

如果您需要经常执行此类搜索,我会继续创建一个新字段,该字段将存储 3 个字段的总和并在其上放置索引。缺点是您必须增加应用程序逻辑。


wdb*_*ley 5

> db.test.drop()
> db.test.insert({ "_id" : 0, "a" : 1, "b" : 1, "c" : 1 })
> db.test.insert({ "_id" : 1, "a" : 1, "b" : 1, "c" : 2 })
> db.test.aggregate([
    { "$project" : { 
        "sum" : { "$add" : ["$a", "$b", "$c" ] } 
    } }, 
    { "$match" : { 
        "sum" : { "$gte" : 4 } 
    } }
])
{ "_id" : 1, "sum" : 4 }
Run Code Online (Sandbox Code Playgroud)