7
db.users.find();

Will return me an array of users:

[{
_id: 123
name: bob
},{
_id: 456
name: tom
}]

I need to map users to another collection by the id, so I would like to get an object back from mongo where the keys are _id and values are the user doc.

i.e.

users = {
123: {_id: 123, name: bob},
456: {_id, 456, name:tom}
}

Then I can access users directly from that object without having to iterate an array to find specific users.

id = 123;
user = users[id];
2
  • 1
    there isn't a way to get data back this way from mongod except by using mapreduce which is not very fast/efficient... of course it can write the results into a new collection so that might save you a step. Commented Jul 13, 2013 at 20:19
  • 1
    I'd suggest you just build a quick client-side index by looping through the returned results. It should be super fast. Commented Jul 13, 2013 at 20:52

2 Answers 2

4

You can't get an object like this one from mongodb, but it's quite easy to build it yourself:

db.users.find(function (err, docs) {
  var users = {};
  docs.forEach(function (doc) {
    users[doc._id] = doc;
  });
  do_whatever_you_want_next(users);
});
Sign up to request clarification or add additional context in comments.

5 Comments

Yeah that is not too bad. Was messing with aggregate and $project to see if I could get it.
Is it still not possible in latest version of mongodb ?
@mandeep_m91, I don't think It'll ever be a part of MongoDB API.
3 years later but I'm looking exactly the same, Do you know if mongo / mongoose support this by default?
6 years later and still looking this functionality, lost lots of time trying to do it with aggregation group, project and mapreduce with no success, it's a pitty to have to rework the resutls taking in account that mongo has already worked them
1

Posting my solution in a more modern syntax:

    const pushSubscriptions = await PushSubscription.find({ token: { $in: tokens } }).exec();
    const userTokens = pushSubscriptions.reduce(
        (result, ps) => {
            result[ps.token] = ps;
            return result;
        },
        {});

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.