Is there a more efficient method to fetch multiple key-value pairs in an array of objects from MongoDB?
I aim to create a function that takes an array of values to search for (e.g. an _id
) and returns an Object with key-value pairs where the key is the original search term.
The data structure could be like this:
'users': [
{
_id: '123',
displayName: 'John Doe',
timezone: 'America/New_York',
},
{
_id: '456',
displayName: 'Jane Doe',
timezone: 'America/New_York',
},
{
_id: '789',
displayName: 'Ken Watanabe',
timezone: 'America/New_York',
}
]
An example input: ['123','789']
The desired output:
{
'123':{
_id: '123',
displayName: 'John Doe',
timezone: 'America/New_York',
},
'789':{
_id: '789',
displayName: 'Ken Watanabe',
timezone: 'America/New_York',
}
}
The retrieved data matches the search parameters and the searched value becomes the new corresponding key.
Currently, I am using:
let data = await db.collection(collection).find( { _id : { $in : _ids } }).toArray();
However, this stores the data in an array of Objects:
[
{
_id: '123',
displayName: 'John Doe',
timezone: 'America/New_York',
},
{
_id: '789',
displayName: 'Ken Watanabe',
timezone: 'America/New_York',
}
]
This can be parsed using Object.entries(), but perhaps there is a more effective way to retrieve the data.
Edit: Marcus has provided a great solution below if you need to solve this issue server-side. Make sure to check it out.
To clarify, I seek a solution that obtains the desired output directly from the database without post-arrival modifications.
Sergio suggested using .aggregate()
, which I will explore now. If I find a solution before others do, I will update with an answer.