node.js - 如何在不使用 unwind 的情况下使用 mongodb 中的数组元素对数据进行排序

标签 node.js arrays mongodb sorting aggregation-framework

这是我的示例数据,我有一个 userId 和一个数组“watchHistory”,“watchHistory”数组包含用户观看的视频列表:

    {
        "_id": "62821344445c30b35b441f11",
        "userId": 579,
        "__v": 0,
        "watchHistory": [
            {
                "seenTime": "2022-05-23T08:29:19.781Z",
                "videoId": 789456,
                "uploadTime": "2022-03-29T12:33:35.312Z",
                "description": "Biography of Indira Gandhi",
                "speaker": "andrews",
                "title": "Indira Gandhi",
                "_id": "628b45df775e3973f3a670ec"
            },
            {
                "seenTime": "2022-05-23T08:29:39.867Z",
                "videoId": 789455,
                "uploadTime": "2022-03-31T07:37:39.712Z",
                "description": "What are some healthy food habits to stay healthy",
                "speaker": "morris",
                "title": "Healthy Food Habits",
                "_id": "628b45f3775e3973f3a670"
            },
            
        ]
    }

我需要匹配 userId,然后我需要使用“watchHistory.seenTime”对其进行排序,seenTime 字段指示用户何时观看视频。所以我需要排序,最后观看的视频应该排在列表的第一位。 我没有使用 unwind 的权限,所以任何人都可以帮助我解决这个问题。谢谢。

最佳答案

如果您使用的是 MongoDB 5.2 及更高版本,则可以在聚合管道中使用 $sortArray 运算符。您的管道应如下所示:

db.collection.aggregate(
  [
    {"$match": 
      { _id: '62821344445c30b35b441f11' }
    },
    {
      "$project": {
        _id: 1,
        "userId": 1,
        "__v": 1,
        "watchHistory": {
          "$sortArray": { input: "$watchHistory", sortBy: { seenTime: -1 }}
        }
      }
    }
  ]
);

请根据您需要过滤的键和值修改“$match”阶段的过滤器。这是 documentation 的链接.

如果不使用unwind,则无法通过聚合管道来完成此操作,但您可以使用update方法和$push运算符,作为这样的解决方法:

db.collection.update({
  _id: "62821344445c30b35b441f11"
},
{
  $push: {
    watchHistory: {
      "$each": [],
      "$sort": {
        seenTime: -1
      },
    }
  }
})

请参阅工作示例here

关于node.js - 如何在不使用 unwind 的情况下使用 mongodb 中的数组元素对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72401920/

相关文章:

node.js - elasticsearch中的可编辑文档字段

node.js - 套接字IO : When to use rooms and when to use namespace?

node.js - 生成 Node 子进程时不遵守 cwd

c - 为什么我的代码有效? C中的数组排序

javascript - 将我的 Javascript 数组放入表中

node.js - Mongoose 没有方法 `connect`

node.js - 您应该向用户发送数据库错误吗?

arrays - 如何自动将纯代码转换为使用可变数组的代码以提高效率?

javascript - 在 NodeJS 中使用 gridfs 按元数据删除文件

javascript - 获取mongoDB模型树结构中的所有父文档