首页 > 解决方案 > 如何在 MongoDB 中手动放置 createdAt (timestamp)

问题描述

如何在 MongoDB 中添加手动 createdAt (timestamp) 字段?

db.getCollection("properties").find({})

这将返回所有属性,这是一个示例:

{ 
    "_id" : ObjectId("5e6b3269617d327b82a71723"), 
    "title" : "Nice and cozy apartment", 
    "category" : "rent", 
    "town" : "London", 
    "price" : NumberInt(3100), 
    "square" : NumberInt(249), 
}

我想要实现的是一个带有时间戳的字段或有关创建特定属性的日期的信息。有人可以帮忙吗?

标签: node.jsmongodb

解决方案


只需在猫鼬模式中放一个键

createdAt:{type: Date, default: Date.now()}; 
//will add automatically putt entry in db whenever document created.

并使用聚合而不是查找(因为您在旧文档中没有密钥 createdAt)作为,

db.orders.aggregate([
                     {
                        $addFields: {
                          "createdAt": { $ifNull: ["$createdAt", Date(manually whenever created)] },
                        }
                    }
                   ])

推荐阅读