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];
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, ...
To get items from an object array, use aggregate (). Let us create a collection with documents − > db.demo459.insertOne( ... { "_id" : 1, ...
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.
$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.
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;
},
{});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With