You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JMeter中Java/Groovy调用MongoDB updateOne时数据覆盖与类型异常

问题

在JMeter性能测试中,需要修改MongoDB文档的嵌套字段。MongoDB Shell/Compass中执行的updateOne脚本可正常修改目标字段(该字段位于object内数组中的object里的number字段),但转为Java/Groovy代码在JMeter中运行时出现异常:不仅覆盖了数组索引0的对象全部内容,还将individualPerson从数组转为对象。尝试传入Java数组、直接发送mongosh查询均无效。

MongoDB Compass有效脚本

db.process.updateOne({_id: "01deda7ec9894a3cbdeb"},
  {$set: {
    "individualPerson.identityDocuments.0.number": "ZZA002204"
  }}
)

JMeter中异常代码

collection.updateOne(Filters.eq("_id", "01deda7ec9894a3cbdeb"), 
  Updates.set("individualPerson.identityDocuments.0.number", "abc123456")
)

解决方案

直接用Document构建$set更新操作,和Mongo Shell语法保持一致,避免驱动对路径解析的异常:

import com.mongodb.client.MongoClients
import com.mongodb.client.MongoCollection
import org.bson.Document
import org.bson.conversions.Bson

// 初始化Mongo连接(根据实际配置修改)
def mongoClient = MongoClients.create("mongodb://your-mongo-host:27017")
def database = mongoClient.getDatabase("your-db-name")
MongoCollection<Document> collection = database.getCollection("process")

// 构建过滤条件和更新语句
Bson filter = new Document("_id", "01deda7ec9894a3cbdeb")
Bson update = new Document("$set", new Document("individualPerson.identityDocuments.0.number", "abc123456"))

// 执行更新
collection.updateOne(filter, update)

// 关闭连接(按需处理)
mongoClient.close()

注意事项

  • 确保JMeter的类路径中包含正确版本的MongoDB Java驱动,版本尽量和MongoDB服务版本匹配,避免语法兼容问题
  • 确认目标文档结构和路径完全匹配:individualPerson是对象类型,其下的identityDocuments是数组,且索引0对应的对象存在
  • 如果individualPerson原本是数组(而非对象),则路径需调整为individualPerson.0.identityDocuments.0.number,同时Compass脚本也需对应修改

内容的提问来源于stack exchange,提问作者Mikemus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:20:43