如何使用_id作为时间戳将createAt字段添加到Mongodb中 [英] How to add createAt field into Mongodb using _id as timestamp

查看:47
本文介绍了如何使用_id作为时间戳将createAt字段添加到Mongodb中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已经存在 200 个数据的用户集合,但我忘记在架构中设置 createAt 字段

I have a user collection with already existed of 200 data and i forgot to set createAt field in schema

现在我想更新所有存在的字段并使用已经是时间戳的 (_id) 添加到数据库中

now i want to update all the existed field and add into database using (_id) which is already a timestamp

所以我想要的只是一个查询,它采用 _id 并转换为日期并保存到现有数据中(我使用的是 robo 3T)

so all i want is a query which take the _id and convert into date and save into existed data (i am using robo 3T )

如果我问了愚蠢的问题,请见谅.我是 mongodb 的新手

please sorry if i have asked silly question. I am new to mongodb

推荐答案

这是 robo mongo 查询,在 mongo 控制台中不起作用.

This is robo mongo query, it won't work in mongo console.

db.getCollection('collectionNameGoesHere').find({}, {
    _id: 1
}).forEach(function (doc) {
    db.getCollection('collectionNameGoesHere').update({
        _id: doc._id
    }, {
        $set: {
            createdAt: doc._id.getTimestamp()
        }
    }, {
        upsert: false,
        multi: true
    })
});

这篇关于如何使用_id作为时间戳将createAt字段添加到Mongodb中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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