MongoDB merges one field into an existing collection using Map / Reduce

I have a MongoDB database with two collections:

  • groups: {group_slug, members}
  • users: {id, display name, groups}

All changes in groups are made by changing the array of group elements to include user identifiers.

I want to synchronize these changes to a user collection using map / reduce. How can I output map / reduction results to an existing collection (but not merge or reduction).

My existing code is here: https://gist.github.com/morgante/5430907

+4
source share
1 answer

How can I output map / reduce results to an existing collection

You really can't do that. And it really is not recommended. There are other solutions:

Solution No. 1:

  • Display card / reduce to temporary collection
  • Run a test task that updates the main data store from the temporary collection
  • Clearing the temporary collection

Honestly, this is a safe way to do this. You can implement some basic repeat logic throughout the loop.

Decision number 2:

  • Queue the changes. (that is, "user subscribes to a group")
  • Update both tables from the separation of workers who listen for such events in the queue.

This solution may require a separate part (queue), but any large system will have such denormalization problems. Thus, this will not be the only place you see it.

+2
source

All Articles