0

Consider a collection of objects having fields like:

{
    id: // String
    type: //Integer
    score: //Double value
}

I would like to query on collection using type and for returned documents divide their scores by their maximum. Consider following query oject:

DBObject searchQuery = new BasicDBObject("type", 2);
collection.find(searchQuery);

With above query it'll return some documents. I want to get maximum of scores among all those documents and then divide all those documents' score by obtained maximum.

How can I do this??

I could find maximum using aggregation as follows:

String propertyToOperateOn = "score";

DBObject match = new BasicDBObject("$match", searchQuery);

DBObject groups = new BasicDBObject("_id", null);
DBObject operation = new BasicDBObject("$max", "$" + propertyToOperateOn);
groups.put("maximum", operation);

DBObject apply = new BasicDBObject("$group", groups);
AggregationOutput output = mongoConstants.IAScores.aggregate(match, apply);

Here output will contain the maximum value. But then how can I update (divide) all documents' scores by this maximum??

I hope there could be better way to do this task, but I'm unable to get it as I'm very much new to mongodb (or any database as such).

1 Answer 1

1

This is technically the same issue as "mongodb: java: How to update a field in MongoDB using expression with existing value", but I'll repeat the answer:

At the moment, MongoDB doesn't allow you to update the value of a field according to an existing value of a field. Which means, you can't do the following SQL:

UPDATE foo SET field1 = field1 / 2;

In MongoDB, you will need to do this in your application, but be aware that this is no longer an atomic operation as you need to read and then write.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.