Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Perform this query on all documents in a collection: this.value = Math.min( this.max, this.value + this.increment) in mongodb

Perform this query on all documents in a collection: this.value = Math.min( this.max, this.value + this.increment) in mongodb

Problem

My documents have all {max, increment, value} and I wish to iterate over all of them with this.value = max( this.max + this.increment).

Currently, I find() all of them, perform value = Math.min( max, value + increment) on each one, then save all of them back to the server (I do this in mongodb).

As you can see, this is a terrible way. I want to perform this instruction to all the documents, serverside only.

How would one do this? A brownie to whoever uses indexes to further optimize this or explains why indexes wouldn't help.

I am using NodeJS for server and native mongodb library.

Problem courtesy of: Discipol

Solution

You could create a map function like this:

db.yourcollection.mapReduce(mapFunctions...)

http://docs.mongodb.org/manual/core/map-reduce/

"Map-reduce operations can handle complex aggregation tasks. To perform map-reduce operations, MongoDB provides the mapReduce command and, in the mongo shell, the db.collection.mapReduce() wrapper method."

http://docs.mongodb.org/manual/tutorial/map-reduce-examples/

Solution courtesy of: Daniel Aranda

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Perform this query on all documents in a collection: this.value = Math.min( this.max, this.value + this.increment) in mongodb

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×