按猫鼬提供的条件数组中的项目顺序对查询结果进行排序 [英] Sorting query results by the order of items in provided conditions array in Mongoose
问题描述
我正在寻找一种基于文档ID数组用Mongoose查询数据库并以将结果按顺序显示给该数组中的Mongoose的方式返回结果的方法.
I am looking for a way to query a database with Mongoose based on an array of document IDs and return the results in the order in which they were presented to Mongoose within that array.
例如,如果我为Mongoose提供了此数组["112", "111", "113"]
并假设所有具有这些ID的文档都存在,那么结果将是一组文档,其顺序为:[{//112},{//111},{//113}]
For example if I provided Mongoose with this array ["112", "111", "113"]
and assuming that all the documents with these IDs exist the result will be an array of documents ordered accordingly as: [{//112},{//111},{//113}]
为了明确起见,我不需要按任何特定的文档字段对数组进行排序-我正在寻找一种方法来告诉Mongoose按条件数组本身中显示的ID的顺序进行排序.这可能吗?
Just to be crystal clear, I don't need to sort the array by any specific document field - I am looking for a way to tell Mongoose to sort by the order of the IDs as presented in the conditions array itself. Is this possible?
推荐答案
考虑以下数据:
db.col.save({ a: "111"})
db.col.save({ a: "112"})
db.col.save({ a: "113"})
db.col.save({ a: "114"})
您可以使用Aggregation Framework的 $ match 过滤掉指定数组和 $ addFields 与 $ indexOfArray 获取index
属性.然后,您可以通过该属性 $ sort 并使用 $ project 删除临时字段.试试:
you can use Aggregation Framework's $match to filter out all the items that are not present in specified array and the $addFields with $indexOfArray to get the index
property. Then you can $sort by that property and use $project to remove temporary field. Try:
db.col.aggregate([
{
$match: { a: { $in: ["112", "111", "113"] } }
},
{
$addFields: {
index: { $indexOfArray: [ ["112", "111", "113"], "$a" ] }
}
},
{
$sort: { index: 1 }
},
{
$project: { index: 0, _id: 0 }
}
])
输出:
{ "a" : "112" }
{ "a" : "111" }
{ "a" : "113" }
这篇关于按猫鼬提供的条件数组中的项目顺序对查询结果进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!