Reputation: 1374
I have a user collection with already existed of 200 data and i forgot to set createAt field in schema
now i want to update all the existed field and add into database using (_id
) which is already a timestamp
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 )
please sorry if i have asked silly question. I am new to mongodb
Upvotes: 0
Views: 1263
Reputation: 14317
You can use any of these two queries to create the createdAt
field with the date/timestamp from _id
. The first one works MongoDb version 4.0+ and the second with MongoDB version 4.2.
Note these work in Mongo Shell, and not tested in robo3T.
db.test.aggregate( [
{
$project: { createdAt: { $toDate: "$_id" } }
}
] ).forEach( doc => db.test.updateOne( { _id: doc._id }, { $set: { createdAt: doc.createdAt } } ) )
db.test.updateMany(
{ },
[
{ $set: { createdAt: { $toDate: "$_id" } } }
]
)
Upvotes: 1
Reputation: 1126
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
})
});
Upvotes: 1