Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - Get back object instead of array from find

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];
like image 666
lostintranslation Avatar asked Jul 13 '13 20:07

lostintranslation


People also ask

How to get items from an object array in MongoDB?

How to get items from an object array in MongoDB? To get items from an object array, use aggregate (). Let us create a collection with documents − > db.demo459.insertOne( ... { "_id" : 1, ...

How to get items from an object array in MySQL?

To get items from an object array, use aggregate (). Let us create a collection with documents − > db.demo459.insertOne( ... { "_id" : 1, ...

How does the find-in array work in MySQL?

The find-in array works on the exact matching. In another word, we can say that a query in which we need to pass all parameters inside the curly base and all parameters depends on the user requirement. The array uses the find method and it is used to return all matching documents from the collection.

Can $lookup return a single object?

$lookup returns array. I doubt you can do any better than project it on next stage. yes currently using $project on next stage but I have to projected 20+ fields also. It would be better if I could return single object in $lookup @AlexBlex It may seem better, but it is not. You assume the lookup matches exactly 1 element.


2 Answers

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;
        },
        {});
like image 25
Miquel Avatar answered Oct 02 '22 09:10

Miquel


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);
});
like image 101
Leonid Beschastny Avatar answered Oct 02 '22 11:10

Leonid Beschastny