1
votes

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);

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

2

2 Answers

2
votes

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);

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

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

And use it like this:

    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);

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.

0
votes

You can use BasicDBObject to add condition.

Try something BasicDBObject query = new BasicDBObject("path", new BasicDBObject("$eq", "_id"); collection.find(query);

Please refer the below link for more information http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/