How to change the structure of MongoDB maps?

When I run Map-Reduce in a Mongo database, I usually get results similar to the following:

{ _id: <some-id>, value: { <first-key>: <first-value>, ... } } 

Is there a way to omit the value: { ... } and directly insert the contents of value into the result? Basically, I would like to get a result that looks like this:

 { _id: <some-id>, <first-key>: <first-value>, ... } 

That way, I could combine the results back into an existing collection that obeys this format.

I also have another question regarding Map-Reduce: is it possible to access another collection using the map or reduce function?

+6
source share
3 answers

MapReduce returns only documents of the form {_id: some_id, value: some_value}

"some_value" does not have to be an inline document, but in most cases it allows you to calculate multiple variables using the Map Reduce function. Documents returned by the Reduce function must be in the same form as they are entered, because the Reduce function can be repeated repeatedly for any given _id value.

For a step-by-step guide to working with Map Reduce, see the Advanced section of MongoDB's cookbook recipe titled “Finding Max and Min Values ​​with Documents with Version” http://cookbook.mongodb.org/patterns/finding_max_and_min/ This should provide the best understanding how Map Reduce works and why the output should be in the format {_id: some_id, value: some_value}

You can perform incremental map reduction, which combines the results of several Map Reduce functions. http://www.mongodb.org/display/DOCS/MapReduce#MapReduce-IncrementalMapreduce

Finally, it is currently not possible to access multiple collections at once using Map Reduce. There is a function request for this feature, but it is not planned to be added to any future versions.
https://jira.mongodb.org/browse/SERVER-970

+6
source

This worked for me:
Assuming you are emitting this or changing it on the map, first set this._id = undefined .
Set the mode for merging.

Check out my example here

0
source

RE: Access to other collections from Map / Reduce functions. What you can do is use "volume" to enter the data m / r needs at runtime. NOTE. In scope, only the SIMPLE collection of objects is used. By simple, I mean the lack of attached documents.

 scope = { People : [{ Name : 'bob', Color : 'blue'}, { Name : 'sally', Color: 'orange'}] } 

The above assembly of objects works fine. In the m / r function, just reference People as a global variable, and you can iterate through your collection, etc.

 scope = { People : [{ Name : 'bob', Color : { Favorite : 'blue'} }, { Name : 'sally', Color : { Favorite : 'orange' } }] } 

The above will not work, depending on the driver you are using, you will receive a Range error and report that the maximum call size is exceeded or something like that. Bonding with simple objects in the area of ​​coverage will remain simple.

0
source

Source: https://habr.com/ru/post/903292/


All Articles