Mongo spring 查询,其中两个字段相等 [英] Mongo spring query where two fields are equal

查看:38
本文介绍了Mongo spring 查询,其中两个字段相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 java 中执行一个查询,其中 path 和 _id 是 mongo 文档的两个字段.

I want to execute a query in java where path and _id are two fields of the mongo document.

我想获取文档中这两个字段相等的结果列表.

I want to get results list where these two fields are equal in the document.

我已尝试使用以下查询.但无法正确检索结果.收到的空列表并非如此.

I have tried using the following query.But could not retrieve the results properly.Received empty list which is not the case.

List<Metadata> MetadataList= ops.find(new Query(Criteria.where("path").is("_id")), Metadata.class);

如何在 mongo 中获得两个字段值相等的结果.

How to get results where two field values are equal in mongo.

推荐答案

您正在寻找的是 $where 在 MongoDB 中的操作符.标准查询操作不会将一个字段的值与另一字段的值进行比较.为此,您需要使用 JavaScript 评估服务器端,它可以实际比较两个字段值:

What you are looking for is the $where operator in MongoDB. Standard query operations do not compare the values of one field against another. In order to do this, you need to employ the JavaScript evaluation server side which can actually compare the two field values:

    BasicQuery query = new BasicQuery(
        new BasicDBObject("$where", "return this._id == this.path")
    );

    <Metadata> MetadataList = ops.find(query, Metadata.class);

或者你可以通过 $redact 管道阶段可用于 聚合框架.

Or you can do the same thing with native operators through the $redact pipeline stage available to the aggregation framework.

很确定在 spring mongo 中还没有 $redact 支持,但是你可以用一个类包装聚合操作来做到这一点:

Pretty sure there is no $redact support in spring mongo as yet, but you can wrap the aggregation operation with a class to do so:

public class CustomAggregationOperation implements AggregationOperation {
    private DBObject operation;

    public CustomAggregattionOperation (DBObject operation) {
        this.operation = operation;
    }

    @Override
    public DBObject toDBObject(AggregationOperationContext context) {
        return context.getMappedObject(operation);
    }
}

像这样使用它:

    Aggregation aggregation = newAggregation(
      new CustomAggregationOperation(
        new BasicDBObject(
          "$redact",
          new BasicDBObject("$cond",
            new BasicDBObject()
              .append("if", new BasicDBObject(
                      "$eq", Arrays.asList("$_id", "$path")
              ))
              .append("then", "$$KEEP")
              .append("else", "$$PRUNE")
          )
        )
      )
    );

    AggregationResults<Metadata> results = ops.aggregate(
            (TypedAggregation<Metadata>) aggregation, Metadata.class);

因此基本的 MongoDB 查询操作不会相互比较字段值.为此,您需要遵循此处的其中一种方法.

So basic MongoDB query operations do not compare field values against each other. To do this you need to follow one of the methods here.

这篇关于Mongo spring 查询,其中两个字段相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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