如何使用查询对象比较Spring Data MongoDB中的2个字段 [英] How to compare 2 fields in Spring Data MongoDB using query object

查看:170
本文介绍了如何使用查询对象比较Spring Data MongoDB中的2个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mongodb中不可能用简单的SQL看起来几乎是自然的.

What seems almost natural in simple SQL is impossible in mongodb.

给出一个简单的文档:

{
    "total_units" : 100,
    "purchased_unit" : 60
}

我想使用spring数据Criteria类(其中"total_units > purchased_units")查询集合.

I would like to query the collection, using spring data Criteria class, where "total_units > purchased_units".

据我所知,它应该与其他任何条件一样琐碎.

To my understanding it should be as trivial as any other condition.

在Spring api上找不到任何支持此功能的东西.

Found nothing to support this on Spring api.

推荐答案

我认为Spring Data API还不支持,但是您可能需要包装

I don't think Spring Data API supports this yet but you may need to wrap the $where query in your Java native DbObject. Note, your query performance will be fairly compromised since it evaluates Javascript code on every record so combine with indexed queries if you can.

本地Mongodb查询:

Native Mongodb query:

db.collection.find({ "$where": "this.total_units > this.purchased_units" });

本地Java查询:

DBObject obj = new BasicDBObject();
obj.put( "$where", "this.total_units > this.purchased_units");

一些 注意事项 您必须在使用$where时查看:

请勿使用全局变量.

Do not use global variables.

$ where评估JavaScript,不能利用索引. 因此,当您表达查询时,查询性能会提高 使用标准的MongoDB运算子(例如$ gt,$ in).一般来说,你 仅当您无法使用其他查询表达查询时,才应使用$ where 操作员.如果必须使用$ where,请尝试至少包含一个 标准查询运算符以过滤结果集.单独使用$ where 需要进行表扫描.使用普通的非$ where查询语句 提供以下性能优势:

$where evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in). In general, you should use $where only when you can’t express your query using another operator. If you must use $where, try to include at least one other standard query operator to filter the result set. Using $where alone requires a table scan. Using normal non-$where query statements provides the following performance advantages:

MongoDB将在$ where之前评估查询的非$ where组件 陈述.如果非$ where语句不匹配任何文档,则MongoDB 将不会使用$ where执行任何查询评估.非$ where 查询语句可以使用索引.

MongoDB will evaluate non-$where components of query before $where statements. If the non-$where statements match no documents, MongoDB will not perform any query evaluation using $where. The non-$where query statements may use an index.

据我所知你做不到 query.addCriteria(Criteria.where("total_units").gt("purchased_units"));

,但可以建议您创建一个额外的计算字段,例如computed_units,这是total_unitspurchased_units之间的区别,您可以按以下方式查询:

but would go with your suggestion to create an additional computed field say computed_units that is the difference between total_units and purchased_units which you can then query as:

Query query = new Query();
query.addCriteria(Criteria.where("computed_units").gt(0));

mongoOperation.find(query, CustomClass.class);

这篇关于如何使用查询对象比较Spring Data MongoDB中的2个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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