0

I am trying to return a field of every object in my collection in form of array using mapReduce function. These are my documents in a collection.

 { _id: '1', name: 'a' },
 { _id: '2', name: 'b' },
 { _id: '4', name: 'c' },
 { _id: '5', name: 'd' },
 { _id: '6', name: 'e' },
 { _id: '7', name: 'f' }

Now i want result in this form ['a','b','c','d','e','f']. How i can achieve it, i tried mapReduce but couldn't get the result in this way.

This is my code

collection.mapReduce( function EachBranch(  ) {
      emit( this.name, this.value);
      }, function ( key, values ) {
      },{ out: { inline: 1 } });

1 Answer 1

2

You'll need to iterate over values in reducer and transform result in desired form.

Example: Try in mongo shell

db.collection.mapReduce(
  function() {
    emit(1, this.name)
  },
  function(k,v){
    var result = {};
    result.names = v;
    return result;
  },
  {out: {inline:1}}
).results[0].value.names;

Based on your sample input documents, you'll get output as:

[ "a", "b", "c", "d", "e", "f" ]

Update: Node.js solution:

collection.mapReduce(
    function () {
        emit(1, this.name)
    },
    function (k, v) {
        var result = {};
        result.names = v;
        return result;
    },
    { out: { inline: 1 } },
    function (err, result) {
        assert.equal(null, err);

        if (result) {
            console.log(result[0].value.names);
        }
        db.close();
    }
);

Note: I'm not handling any error so please do defensive coding.

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

5 Comments

See my NOTE above. I clearly mentioned that I'm not doing any error check. If there is no result, you'll get error. I am leaving error handling on you. Please note, SO is not a coding service. We are here to help but not to solve assignments or do job.
I understand, the issue is in your code the results is undefined
Have you had a try? Copy above code and run in shell.
in my understanding .results.... is part of mongo and can't be used in nodejs? So I have to map the returned values and take out name from it?
What is emit()?

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.