我需要您的帮助。”“如何根据它们的索引按ObjectIDs
数组在集合中搜索文档?
我有一个包含播放列表ID的数组,它们按照严格的顺序添加到其中。我需要按索引的顺序找到它们。
我尝试使用$in
运算符,它可以正确找到所有内容,但不能按它们在数组中存储的顺序进行查找。是否有可能使这个命令得到遵守?
const playlisIds = [
"5d8b4540a4f4ee24a40c8359",
"5d8b47b1a4f4ee24a40c835e",
"5d8e1457a513c112c0d8b42f",
"5d8e1441a513c112c0d8b42a"
];
const playlists = await Playlist.find({ _id: {$in: playlisIds } })
playlists = [
{
_id: "5d8e1441a513c112c0d8b42a", //index 3 in playlisIds
// ...other fields``
},
{
_id: "5d8b47b1a4f4ee24a40c835e" //index 1 in playlisIds
// ...other fields
},
{
_id: "5d8b4540a4f4ee24a40c8359" //index 0 in playlisIds
// ...other fields``
},
{
_id: "5d8e1457a513c112c0d8b42f" //index 2 in playlisIds
// ...other fields
}
]
一次搜索一个文档将非常昂贵。
const playlists = playlisIds.map(async (id) => await Playlist.findById(id)) // not good practice ((
const playlisIds = [
"5d8b4540a4f4ee24a40c8359",
"5d8b47b1a4f4ee24a40c835e",
"5d8e1457a513c112c0d8b42f",
"5d8e1441a513c112c0d8b42a"
];
const playlists = await Playlist.find({ _id: {$in: playlisIds } })
playlists = [
{
_id: "5d8b4540a4f4ee24a40c8359", //index 0 in playlisIds
// ...other fields
},
{
_id: "5d8b47b1a4f4ee24a40c835e"//index 1 in playlisIds
// ...other fields
},
{
_id: "5d8e1457a513c112c0d8b42f"//index 2 in playlisIds
// ...other fields
},
{
_id: "5d8e1441a513c112c0d8b42a"//index 3 in playlisIds
// ...other fields
},
]
我希望它像上面一样。