如何 select 字段总和大于 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.
}}
优点是简单直观,缺点:
requires that the database processes the JavaScript expression or
function for each document in the collection.
如果您需要经常执行此类搜索,我会继续创建一个新字段,其中将存储 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 }
这是一个旧的 post 但这可能有助于寻找其他解决方案的人。我发现这比 $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 }
使用 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.
}}
优点是简单直观,缺点:
requires that the database processes the JavaScript expression or function for each document in the collection.
如果您需要经常执行此类搜索,我会继续创建一个新字段,其中将存储 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 }
这是一个旧的 post 但这可能有助于寻找其他解决方案的人。我发现这比 $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 }