如何按“日期”字段对“$lookup”结果数组进行排序

发布于 2025-01-19 07:38:43 字数 723 浏览 1 评论 0原文

我正在尝试对通过 $lookup 通过名为 createdAt 的字段计算的数组(降序)进行排序,该字段包含 Date 对象:

[
   {
      "$lookup": {
         "from": "activities",
         "localField": "activities",
         "foreignField": "_id",
         "as": "activities"
      }
   },
   {
      "$sort": {
         "activities.createdAt": -1
      }
   },
   {
      "$project": {
         "_id": false,
         "updatedAt": false,
         "activities._id": false,
         "activities.game": false,
         "activities.updatedAt": false,
         "activities.__v": false,
         "__v": false
      }
   }
]

activities 字段已正确“填充”,但未对结果进行排序。

I'm trying to sort an array (descending) that gets computed through a $lookup by a field called createdAt which contains a Date object:

[
   {
      "$lookup": {
         "from": "activities",
         "localField": "activities",
         "foreignField": "_id",
         "as": "activities"
      }
   },
   {
      "$sort": {
         "activities.createdAt": -1
      }
   },
   {
      "$project": {
         "_id": false,
         "updatedAt": false,
         "activities._id": false,
         "activities.game": false,
         "activities.updatedAt": false,
         "activities.__v": false,
         "__v": false
      }
   }
]

The activities field is being "populated" correctly but it's not sorting the results.

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

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

发布评论

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

评论(1

梦过后 2025-01-26 07:38:43

尝试用像波纹管这样的管道来替换查找。
如果您希望对数组进行排序,则可以在该管道中进行。

如果这不是您需要的,那么如果您可以添加一些示例数据和预期的输出。

aggregate(
[{"$lookup": 
   {"from": "activities",
    "localField": "activities",
    "foreignField": "_id",
    "pipeline": [{"$sort": {"createdAt": -1}}],
    "as": "activities"}}])

Try to replace your lookup with a lookup with pipeline like the bellow.
If you want the array to be sorted, you can do it inside that pipeline.

If this isn't what you need if you can add some sample data and expected output.

aggregate(
[{"$lookup": 
   {"from": "activities",
    "localField": "activities",
    "foreignField": "_id",
    "pipeline": [{"$sort": {"createdAt": -1}}],
    "as": "activities"}}])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文