繁体   English   中英

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

[英]How to select where sum of fields is greater than a value in MongoDB

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

SELECT * FROM table WHERE (field1+field2+field3) > 1

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

最简单的方法是使用$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.
}}

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

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

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

> 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 }

这是一篇旧帖子,但这可能有助于寻找其他解决方案的人。 我发现这比$where.aggregate()更简单。

> db.foo.insert({"a": 17, "b": 8})
> db.foo.find({$expr: {$gt: [{$add: ["$a", "$b"]}, 25]}})   // no result
> db.foo.find({$expr: {$gt: [{$add: ["$a", "$b"]}, 24]}})
{ "_id" : ObjectId("602acf55a69fb564c11af7db"), "a" : 17, "b" : 8 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM