gpt4 book ai didi

javascript - Mongodb sort Aggregation in same order ids 在过滤器上传递

转载 作者:行者123 更新时间:2023-12-05 03:20:18 26 4
gpt4 key购买 nike

我想知道是否有可能使结果的当前顺序与过滤时传递的顺序相同。

假设我们有一组 IDS:

var arrayValues = [1,3,2]

我想聚合这些值,但保持结果与我在上述数组中传递的顺序相同。

 var result = Item.aggregate([{ $match: { _id: { $in: arrayValues } }}])

我希望结果与作为 _id 值传入的数组值的顺序相同。

示例结果:

result = [{ _id: 1 },{ _id: 3 },{ _id: 2 }]

最佳答案

您可以为此使用 indexOfArray:

db.collection.aggregate([
{$match: {_id: {$in: arrayValues}}},
{$set: {index: {$indexOfArray: [arrayValues, "$_id"]}}},
{$sort: {index: 1}},
{$unset: "index"}
])

看看它是如何在 playground example 上工作的

关于javascript - Mongodb sort Aggregation in same order ids 在过滤器上传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73209615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com