如何将 BSON 时间戳从 Mongo 变更流转换为日期? [英] How to convert BSON Timestamp from Mongo changestream to a date?

查看:98
本文介绍了如何将 BSON 时间戳从 Mongo 变更流转换为日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开始使用 Mongo 中的 Changestream.在我当前的设置中,缝合函数将更改日志事件插入到修订集合中.但是,当我从集合中读取数据时,我无法转换 Timestamp 字段.我尝试了以下 2 次尝试:

I am getting started with the Changestream in Mongo. In my current setup a stitch functions inserts the changelog events into a revision collection. However when I read data from the collection, I can't convert the Timestamp fields. I have tried with the following 2 attempts:

1) 管道

[
    {
        $match: {
            'documentKey._id': _id,
        },
    },
    {
        $sort: { _id: -1 },
    },
    {
        $addFields: {
            convertedDate: { $toDate: 'clusterTime' },
        },
    },
]

但它给出了错误:Error parsing date string 'clusterTime';0:不允许将时区标识符作为字符串的一部分传递 'c';6:双时区规范'r'

2) bson Timestamp 类

import { Timestamp } from 'bson';
const asTimestampInstance = new Timestamp(v.clusterTime);

但是这里打字稿给了我错误:预期有 2 个参数,但得到 1.ts(2554)index.d.ts(210, 30):未提供high"的参数.

But here typescript gives me the error: Expected 2 arguments, but got 1.ts(2554) index.d.ts(210, 30): An argument for 'high' was not provided.

在 Altas 中,clustertime 正确地看起来像一个时间戳:

In Altas, the clustertime correctly looks like a timestamp:

我希望我只是错过了一些简单的东西:)

I hope that I am just missing something simple :)

推荐答案

很遗憾 $toDate 不能直接使用时间戳.至少在 v4.0 中不是.

Unfortunately $toDate doesn't work with timestamps directly. At least not in v4.0.

参数应该是数字、字符串或 ObjectId.

The argument should be either a number, a string, or an ObjectId.

您需要先将 Timestamp 转换为字符串:

You need to convert Timestamp to string first:

    $addFields: {
        convertedDate: { $toDate: {$dateToString:{date:"$clusterTime"}} },
    },

这篇关于如何将 BSON 时间戳从 Mongo 变更流转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆