【问题标题】:How can I log actual queries to MongoDB with mongo java driver in Micronaut application如何在 Micronaut 应用程序中使用 mongo java 驱动程序将实际查询记录到 MongoDB
【发布时间】:2021-09-03 06:40:26
【问题描述】:

我将 mongo 记录器设置如下

<logger name="org.mongodb" level="debug"/>

当我在 Micronuat 应用程序中使用 java 驱动程序运行查询时

DEBUG org.mongodb.driver.protocol.command - Sending command '{"aggregate": "product.category", "pipeline": [{"$match": {"$and": [{"_id": {"$oid": "60c4aed3afb396342bf90802"}}, {"subCategory._id": {"$oid": "60cc5dd52b5cf415ded7de5d"}}]}}, {"$group": {"_id": 1, "n": {"$sum": 1}}}], "cursor": {}, "$db": "FeteBird-Product", "lsid": {"id": {"$binary": {"base64": "9UGXhsvnSZ+FXRCDwsiyWA==", "subType": "04"}}}}'

但是,如果我复制此命令并尝试在 mongoshell 中运行,它将无法工作,我如何才能显示它正在生成的确切查询。这样我就可以运行该查询并在控制台上查看输出

【问题讨论】:

  • 您所看到的是查询的完整表示,聚合和管道的第一部分是查询,其余的只是有关您执行查询的数据库的附加信息,请检查 mongodb -shell sintax 但所有信息都在那里
  • 如何执行该命令

标签: java mongodb mongo-java-driver mongo-java micronaut-data


【解决方案1】:

尝试使用 runCommand 运行您的命令

mongo shell> use database_name
mongo shell> db.runCommand({"aggregate": "product.category", "pipeline": [{"$match": {"$and": [{"_id": {"$oid": "60c4aed3afb396342bf90802"}}, {"subCategory._id": {"$oid": "60cc5dd52b5cf415ded7de5d"}}]}}, {"$group": {"_id": 1, "n": {"$sum": 1}}}], "cursor": {}, "$db": "FeteBird-Product", "lsid": {"id": {"$binary": {"base64": "9UGXhsvnSZ+FXRCDwsiyWA==", "subType": "04"}}}})

【讨论】:

  • 知道如何将 60c4aed3afb396342bf90802 转换为 BSON,运行上述命令时出现异常
  • com.mongodb.MongoCommandException: 命令失败,错误 14 (TypeMismatch): 'BSON 字段'OperationSessionInfo.lsid.id' 是错误的类型'object',服务器localhost 上的预期类型'binData'' :27017。完整响应是 {"ok": 0.0, "errmsg": "BSON field 'OperationSessionInfo.lsid.id' is wrong type 'object', expected type 'binData'", "code": 14, "codeName": “类型不匹配”}
  • 实际上错误说要修复 OperationSessionInfo.lsid.id 字段,而不是 subCategory._id 字段。 $oid 是构建ObjectId 实例的一种方式
  • db.runCommand( {"aggregate": "product.category", "pipeline": [ {"$match": {"$and": [{"_id": "60c4aed3afb396342bf90802"} , {"subCategory._id": "60cc5dd52b5cf415ded7de5d"}]} } ], "cursor": {}, "$db": "FeteBird-Product"} )这可行,但有很多修改
  • 您可以尝试将"lsid": {"id": {"$binary": {"base64": "9UGXhsvnSZ+FXRCDwsiyWA==", "subType": "04"}}} 替换为"lsid: {"id": BinData(4, "9UGXhsvnSZ+FXRCDwsiyWA==")}
猜你喜欢
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 2012-05-24
  • 1970-01-01
相关资源
最近更新 更多