gpt4 book ai didi

mongodb - 蒙戈 : How to convert all entries using a long timeStamp to an ISODate?

转载 作者:可可西里 更新时间:2023-11-01 09:11:22 26 4
gpt4 key购买 nike

我有一个包含累积条目/字段的当前 Mongo 数据库

{
name: "Fred Flintstone",
age : 34,
timeStamp : NumberLong(14283454353543)
}

{
name: "Wilma Flintstone",
age : 33,
timeStamp : NumberLong(14283454359453)
}

等等……

问题:我想将数据库中的所有条目转换为它们相应的 ISODate - 如何做到这一点?

期望的结果:

{
name: "Fred Flintstone",
age : 34,
timeStamp : ISODate("2015-07-20T14:50:32.389Z")
}

{
name: "Wilma Flintstone",
age : 33,
timeStamp : ISODate("2015-07-20T14:50:32.389Z")
}

我尝试过的事情

 >db.myCollection.find().forEach(function (document) {
document["timestamp"] = new Date(document["timestamp"])

//Not sure how to update this document from here
db.myCollection.update(document) //?
})

最佳答案

使用聚合管道进行更新操作,只需运行以下更新操作:

db.myCollection.updateMany(
{ },
[
{ $set: {
timeStamp: {
$toDate: '$timeStamp'
}
} },
]
])

在您最初的尝试中,您几乎就成功了,您只需要调用 save()修改文档上的方法来更新它,因为该方法使用 insert update 命令。在上面的例子中,文档包含一个 _id 字段,因此是 save()方法等同于 update() upsert 选项设置为 true 且查询谓词在 _id 字段上的操作:

db.myCollection.find().snapshot().forEach(function (document) {
document["timestamp"] = new Date(document["timestamp"]);
db.myCollection.save(document)
})

上面类似于显式调用 update() 您之前尝试过的方法:

db.myCollection.find().snapshot().forEach(function (document) {
var date = new Date(document["timestamp"]);
var query = { "_id": document["_id"] }, /* query predicate */
update = { /* update document */
"$set": { "timestamp": date }
},
options = { "upsert": true };

db.myCollection.update(query, update, options);
})

对于相对较大的集合大小,您的数据库性能会很慢,建议使用 mongo bulk updates为此:

MongoDB 版本 >= 2.6 和 < 3.2:

var bulk = db.myCollection.initializeUnorderedBulkOp(),
counter = 0;

db.myCollection.find({"timestamp": {"$not": {"$type": 9 }}}).forEach(function (doc) {
bulk.find({ "_id": doc._id }).updateOne({
"$set": { "timestamp": new Date(doc.timestamp") }
});

counter++;
if (counter % 1000 === 0) {
// Execute per 1000 operations
bulk.execute();

// re-initialize every 1000 update statements
bulk = db.myCollection.initializeUnorderedBulkOp();
}
})

// Clean up remaining operations in queue
if (counter % 1000 !== 0) bulk.execute();

MongoDB 版本 3.2 及更新版本:

var ops = [],
cursor = db.myCollection.find({"timestamp": {"$not": {"$type": 9 }}});

cursor.forEach(function (doc) {
ops.push({
"updateOne": {
"filter": { "_id": doc._id } ,
"update": { "$set": { "timestamp": new Date(doc.timestamp") } }
}
});

if (ops.length === 1000) {
db.myCollection.bulkWrite(ops);
ops = [];
}
});

if (ops.length > 0) db.myCollection.bulkWrite(ops);

关于mongodb - 蒙戈 : How to convert all entries using a long timeStamp to an ISODate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31519648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com