如何在MongoDB中选择字段总和大于某个值的位置 [英] How to select where sum of fields is greater than a value in MongoDB

查看:239
本文介绍了如何在MongoDB中选择字段总和大于某个值的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using MongoDB, How would I write this regular SQL statement?

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

我一直在弄乱$ group,$ project,$ add等.我觉得我在解决方案中四处跳舞,但无法弄清楚.

I've been messing with $group, $project, $add, etc. I feel like I'm dancing all around the solution but can't figure it out.

推荐答案

最简单的方法是使用

The easiest way to do this is by using $where (I am not telling that it is not possible to do this with aggregation)

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

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

The pros of it is that it is easy and intuitive, whereas cons:

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

requires that the database processes the JavaScript expression or function for each document in the collection.

如果您需要经常执行这种搜索,我将继续创建一个新字段,该字段中将存储3个字段的总和,并为其添加索引.缺点是您必须增加应用逻辑.

If you need to perform this kind of searches often, I would go ahead and create a new field which will have a sum of 3 fields stored in it and put an index on it. The downside is that you have to increase your app logic.

这篇关于如何在MongoDB中选择字段总和大于某个值的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆