gpt4 book ai didi

json - mongodb printjson 会输出 ObjectId 到结果,不能用于 JSON.parse

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

我像这样运行我的 mongo shell 脚本:

mongo --quiet myscript.js > /tmp/my.json

我在 myscript.js 中使用 printjson。 mongodb printjson 会将 ObjectId 输出到 my.json,像这样:

"_id" : ObjectId("5444a932ca62bbcba14a1082")

我从 mongo shell 中读取了一些源代码。 printjson 将为 ObjectId 对象运行此代码。

> x._id.tojson
function (){
return this.toString();
}

在 mongo 2.2 版本之后,ObjectId("507c7f79bcf86cd7994f6c0e").toString() 将返回以下字符串:

ObjectId("507c7f79bcf86cd7994f6c0e")

这不是我想要的。我使用 ObjectId("507c7f79bcf86cd7994f6c0e").valueOf()

这将返回以下字符串:

507c7f79bcf86cd7994f6c0e

最后,我在 myscript.js 中添加一行:

ObjectId.prototype.toString = function() { return '"' + this.valueOf() + '"'; }

我解决了我的问题。但我不喜欢更改 toString() 的原始行为。有没有更好的解决方案?

最佳答案

根据脚本中的内容,您可以使用 mongoexport 而不是 mongo 来解决您的问题。 mongoexport JSON 输出使用 extended json 的“严格模式” ,这是有效的 JSON,可以被其他非 mongo JSON 工具解析。

要使用此技术,您需要将查询从“shell 模式”转换为“严格模式”,将数据库名称和集合名称作为参数传递,并为您的 shell 正确引用。例如,采用为 mongo shell 编写的查询:

db.myItemsCollection.find({creationDate: {$gte: ISODate("2016-09-29")}})

并使用 mongoexport 将其转换为等效的 shell 表达式:

mongoexport --jsonArray -d myDbName -c myItemsCollection -q '{"creationDate": {"$gte": {"$date": "2016-09-29T00:00Z"}}}'

此输出可以通过管道传输到 json_ppjq 或其他需要有效 JSON 作为输入的工具。

关于json - mongodb printjson 会输出 ObjectId 到结果,不能用于 JSON.parse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26459585/

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