强制 mongodb 输出严格 JSON

Force mongodb to output strict JSON

我想在其他使用 JSON 的程序中使用某些 MongoDB 命令的原始输出。当我在 mongo shell 中执行 运行 命令时,它们表示 Extended JSON,"shell mode" 中的字段,具有特殊字段,例如 NumberLongDate,以及 Timestamp。我在文档中看到了对 "strict mode" 的引用,但我看不到为 shell 打开它的方法,也没有办法在 db.serverStatus() 之类的 运行 命令中打开它 do输出严格JSON,如mongodump。如何强制 Mongo 输出符合标准的 JSON?

several questions 个关于这个主题的,但我觉得他们的回答都不是特别令人满意。

MongoDBshell讲Javascript,所以答案很简单:用JSON.stringify()。如果你的命令是db.serverStatus(),那么你可以简单地这样做:

JSON.stringify(db.serverStatus())

这不会输出每个字段的正确 "strict mode" 表示({ "floatApprox": <number> } 而不是 { "$numberLong": "<number>" }),但是如果您关心的是符合标准 JSON 出来,这样就可以了。

我还没有在 mongo shell 中找到执行此操作的方法,但作为解决方法,mongoexport 可以 运行 查询并且其输出使用严格模式并且可以通过管道传输到其他需要 JSON 输入的命令(例如 json_ppjq)。例如,假设您有以下 mongo shell 命令来 运行 查询,并且您想要使用该数据创建管道:

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

将 mongo shell 命令转换为此 shell 命令,为了举例,将管道转换为 `json_pp:

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

您需要将查询转换为严格模式格式,并将数据库名称和集合名称作为参数传递,并为您的 shell 正确引用,如下所示。

要基于@jbyler 的答案,您可以在获取数据后使用 sed 删除 numberLongs - 也就是说,如果您使用的是 linux.

mongoexport --jsonArray -d dbName -c collection -q '{fieldName: {$regex: ".*turkey.*"}}' | sed -r 's/\{ "[$]numberLong" : "([0-9]+)" }/""/g' | json_pp

编辑:这将转换给定的文档,但不适用于文档列表。将 find 更改为 findOne

添加

.forEach(function(results){results._id=results._id.toString();printjson(results)})`

findOne()会输出有效的JSON.

示例:

db
  .users
  .findOne()
  .forEach(function (results) {
    results._id = results._id.toString();
    printjson(results)
  })

来源:https://www.mydbaworld.com/mongodb-shell-output-valid-json/

如果是 findOne

JSON.stringify(db.Bill.findOne({'a': '123'}))

在游标的情况下

db.Bill.find({'a': '123'}).forEach(r=>print(JSON.stringify(r)))

print('[') + db.Bill.find().limit(2).forEach(r=>print(JSON.stringify(r) + ',')) + print(']')

会输出

[{a:123},{a:234},]

the last one will have a ',' after the last item...remove it