gpt4 book ai didi

javascript - Mongodb 聚合以对数组中最常见的项目进行排序?

转载 作者:行者123 更新时间:2023-12-01 21:27:46 24 4
gpt4 key购买 nike

集合中的一个项目包含一个字符串数组。我想查找数组中具有最匹配元素的项目并对其进行排序。

考虑一个集合:

[
{
"item_name":"Item_1",
"tags":["A","B","C","D","E"]
},
{
"item_name":"Item_2",
"tags":["A","B","D","E","G"]
},
{
"item_name":"Item_3",
"tags":["B","C","E","H"]
}

]

我想根据 ["B","D","G","F"] 这样的数组对集合进行排序这将返回

[

{
"item_name":"Item_2",
"tags":["A","B","D","E","G"]
},
{
"item_name":"Item_1",
"tags":["A","B","C","D","E"]
},
{
"item_name":"Item_3",
"tags":["B","C","E","H"]
}

]

预期顺序为 Item_2、Item_1,然后是 Item_3,因为

  • Item_2 匹配 3 个项目(“B”、“D”和“G”)
  • 然后是具有 2 个匹配项(“B”和“D”)的 Item_1
  • 最后 Item_3 有 1 个匹配(“B”)

如果不在mongodb中,JavaScript方法也会受到赞赏

最佳答案

如果 tags 中的值是唯一的,您可以使用 tags 的交集大小和使用 $size 的查询数组和 $setIntersection

db.collection.aggregate([
{
$set: {
matchedCount: {
$size: {
$setIntersection: ["$tags", ["B","D","G","F"]]
}
}
}
},
{
$sort: {
matchedCount: -1
}
}
])

关于javascript - Mongodb 聚合以对数组中最常见的项目进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62877287/

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