如何仅在MongoDB聚合中获得数组的前3个值

发布于 2025-02-01 00:49:35 字数 621 浏览 3 评论 0原文

我有一个收藏

"_id": {
    "$oid": "f3187b40cacac21f88c60"
  },
  "recipeId": "3da8f8ddfa600294b278d",
  "dish": "abc",
  
  "Profile": {
    "Tag": [
      {
        "Tag": "X",
        "ratios": 5.9751602852
      },
      {
        "Tag": "Y",
        "ratios": 53.9308283909
      },
      {
        "Tag": "Z",
        "ratios": 12.3244466278
      },
      {
        "Tag": "A",
        "ratios": 13.1145449121
      },
      {
        "Tag": "B",
        "ratios": 1.3848693181
      },
      {
        "Tag": "C",
        "ratios": 1.2996209903
      }

的集合中的收藏,我想要配方,菜肴和top3标签及其比例。

I have a collection which look like this

"_id": {
    "$oid": "f3187b40cacac21f88c60"
  },
  "recipeId": "3da8f8ddfa600294b278d",
  "dish": "abc",
  
  "Profile": {
    "Tag": [
      {
        "Tag": "X",
        "ratios": 5.9751602852
      },
      {
        "Tag": "Y",
        "ratios": 53.9308283909
      },
      {
        "Tag": "Z",
        "ratios": 12.3244466278
      },
      {
        "Tag": "A",
        "ratios": 13.1145449121
      },
      {
        "Tag": "B",
        "ratios": 1.3848693181
      },
      {
        "Tag": "C",
        "ratios": 1.2996209903
      }

In the output of aggregation I want recipeId,dish and top3 tags along with its ratios.I am trying to create a table of recipeId , dish , tags and ratios in Redash.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深空失忆 2025-02-08 00:49:35

查询

  • $ sortArray在mongodb 5.2中添加了
  • 波纹管与Undind一起使用,因为您可能没有5.2版本的
  • 放松并进行排序,然后返回,最后仅使用$ slice

playmongo

aggregate(
[{"$unwind": "$Profile.Tag"}, 
 {"$sort": {"Profile.Tag.ratios": -1}},
 {"$group": 
   {"_id": "$_id",
    "recipeId": {"$first": "$recipeId"},
    "dish": {"$first": "$dish"},
    "Tag": {"$push": "$Profile.Tag"}}},
 {"$set": {"Profile": {"Tag": {"$slice": ["$Tag", 3]}},
  "Tag": "$REMOVE"}}])

Query

  • $sortArray is added in MongoDB 5.2
  • the bellow works with unwind because probably you dont have the 5.2 version
  • unwind and sort, group back, and finally take the first 3 only with $slice

Playmongo

aggregate(
[{"$unwind": "$Profile.Tag"}, 
 {"$sort": {"Profile.Tag.ratios": -1}},
 {"$group": 
   {"_id": "$_id",
    "recipeId": {"$first": "$recipeId"},
    "dish": {"$first": "$dish"},
    "Tag": {"$push": "$Profile.Tag"}}},
 {"$set": {"Profile": {"Tag": {"$slice": ["$Tag", 3]}},
  "Tag": "$REMOVE"}}])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文