本文介绍了强制mongodb输出严格的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在其他使用JSON的程序中使用某些MongoDB命令的原始输出.当我在mongo shell中运行命令时,它们表示扩展JSON , "shell模式"中的字段,并带有特殊字段,例如NumberLongDateTimestamp.我在文档中看到了严格模式"的参考,但是我看不到在外壳程序上打开它的方法,或者在 do 输出严格JSON的情况下运行诸如db.serverStatus()之类的命令的方法,就像mongodump.如何强制Mongo输出符合标准的JSON?

I want to consume the raw output of some MongoDB commands in other programs that speak JSON. When I run commands in the mongo shell, they represent Extended JSON, fields in "shell mode", with special fields like NumberLong , Date, and Timestamp. I see references in the documentation to "strict mode", but I see no way to turn it on for the shell, or a way to run commands like db.serverStatus() in things that do output strict JSON, like mongodump. How can I force Mongo to output standards-compliant JSON?

其他 ,但我找不到他们的回答特别令人满意.

There are several other questions on this topic, but I don't find any of their answers particularly satisfactory.

推荐答案

MongoDB shell使用Java语言,因此答案很简单:使用JSON.stringify().如果您的命令是db.serverStatus(),则只需执行以下操作:

The MongoDB shell speaks Javascript, so the answer is simple: use JSON.stringify(). If your command is db.serverStatus(), then you can simply do this:

JSON.stringify(db.serverStatus())

这不会为每个字段({ "floatApprox": <number> }而不是{ "$numberLong": "<number>" })输出正确的严格模式"表示形式,但是如果您关心的是取出符合标准的JSON,则可以技巧.

This won't output the proper "strict mode" representation of each of the fields ({ "floatApprox": <number> } instead of { "$numberLong": "<number>" }), but if what you care about is getting standards-compliant JSON out, this'll do the trick.

这篇关于强制mongodb输出严格的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:20