如何使用Mongosh 1.10.5版本获取合法JSON格式输出?
问题
使用Mongosh 1.10.5执行以下查询时,返回结果为BJSON(Binary JSON)格式,无法用jq工具过滤键值对:
mongosh "mongodb+srv://testuser:xxxxxx@serverlesspentestdb.bu2mw.mongodb.net/testdb?retryWrites=true&w=majority" --quiet --eval 'db.testcheck.find({ "submittedAt": { $gt: ISODate("2023-10-06T00:00:00.000Z") }, "email": { $not: { $regex: /@(example\.com|example\.ai)$/i } } })'
尝试用EJSON转换时报错TypeError: EJSON.stringfy is not a function,命令如下:
mongosh "mongodb+srv://testuser:xxxxxx@serverlesspentestdb.bu2mw.mongodb.net/testdb?retryWrites=true&w=majority" --quiet --eval 'EJSON.stringfy(db.testcheck.find({ "submittedAt": { $gt: ISODate("2023-10-06T00:00:00.000Z") }, "email": { $not: { $regex: /@(example\.com|example\.ai)$/i } } }))'
如何修改查询以获取可被jq处理的JSON格式输出?
解决方法
方案1:使用mongosh内置的--jsonOutput参数
这是最直接的方式,添加该参数后mongosh会直接输出标准JSON格式:
mongosh "mongodb+srv://testuser:xxxxxx@serverlesspentestdb.bu2mw.mongodb.net/testdb?retryWrites=true&w=majority" --quiet --jsonOutput --eval 'db.testcheck.find({ "submittedAt": { $gt: ISODate("2023-10-06T00:00:00.000Z") }, "email": { $not: { $regex: /@(example\.com|example\.ai)$/i } } })'
方案2:修正EJSON方法拼写并转换游标为数组
你之前的错误是把EJSON.stringify拼写成了EJSON.stringfy,同时find()返回的是游标对象,需要先转为数组才能正确序列化:
mongosh "mongodb+srv://testuser:xxxxxx@serverlesspentestdb.bu2mw.mongodb.net/testdb?retryWrites=true&w=majority" --quiet --eval 'EJSON.stringify(db.testcheck.find({ "submittedAt": { $gt: ISODate("2023-10-06T00:00:00.000Z") }, "email": { $not: { $regex: /@(example\.com|example\.ai)$/i } } }).toArray())'
方案3:使用标准JSON.stringify
如果不需要处理MongoDB特殊类型(如ObjectId、ISODate),也可以直接用原生JSON序列化:
mongosh "mongodb+srv://testuser:xxxxxx@serverlesspentestdb.bu2mw.mongodb.net/testdb?retryWrites=true&w=majority" --quiet --eval 'JSON.stringify(db.testcheck.find({ "submittedAt": { $gt: ISODate("2023-10-06T00:00:00.000Z") }, "email": { $not: { $regex: /@(example\.com|example\.ai)$/i } } }).toArray())'
说明:如果结果包含MongoDB专属类型,
JSON.stringify会将其转为{"$date":"2023-10-06T00:00:00.000Z"}这类格式,jq依然可以正常解析;EJSON.stringify则会生成更贴合MongoDB规范的EJSON格式,两者都能被jq处理。
内容的提问来源于stack exchange,提问作者devops-admin
相关产品推荐
相关产品推荐

