我在 MongoDB 中有以下 json 数据,需要使用 TraceId 作为搜索键来更新状态字段。
{
"_id" : ObjectId("59cd4ec748eecac127d4ed11"),
"mode" : "Email",
"text" : "template",
"subject" : "EIS Order Number EO17000988 - Notice Type SOA",
"scenario" : "SendCustomerNoticeGenericEvent",
"system" : "CIS",
"traceId" : NumberInt(676517451),
"timestamp" : ISODate("2017-09-27T19:20:10.860+0000"),
"recipients" : [
{
"status" : "Delivered",
"firstName" : " ",
"lastName" : " ",
"address" : "ao084x@att.com",
"type" : "to"
}
],
"from" : {
"firstName" : "AT&T Enterprise Notifications",
"lastName" : " ",
"address" : "blink@zld00826.vci.att.com"
}
}
当我使用 Spring boot 框架运行下面的 java 代码时,我总是收到错误“位置运算符没有从查询中找到所需的匹配。未展开的更新:recipients.$.status”。但是,如果我将位置运算符 $ 更改为数字 0,则代码有效。为什么 $ 符号在这里不起作用?请帮忙。提前致谢。
MongoCollection<Document> collection = db.getCollection("notifyHistoryDbmS");
BasicDBObject updateDoc = new BasicDBObject("$set", new BasicDBObject("recipients.$.status", status));
BasicDBObject query = new BasicDBObject().append("traceId", Integer.valueOf(traceId));
UpdateResult statusUpdate = collection.updateOne(query, updateDoc);
最佳答案
您尝试执行的操作仅受 MongoDB 预览版 (3.5.12+) 支持。请参阅:https://jira.mongodb.org/browse/SERVER-1243
db.notifyHistoryDbmS.insertOne({
"_id" : ObjectId("59cd4ec748eecac127d4ed11"),
"mode" : "Email",
"text" : "template",
"subject" : "EIS Order Number EO17000988 - Notice Type SOA",
"scenario" : "SendCustomerNoticeGenericEvent",
"system" : "CIS",
"traceId" : NumberInt(676517451),
"timestamp" : ISODate("2017-09-27T19:20:10.860+0000"),
"recipients" : [
{
"status" : "Delivered",
"firstName" : " ",
"lastName" : " ",
"address" : "ao084x@att.com",
"type" : "to"
}
],
"from" : {
"firstName" : "AT&T Enterprise Notifications",
"lastName" : " ",
"address" : "blink@zld00826.vci.att.com"
}
});
然后以下调用会导致您看到的错误消息。
db.notifyHistoryDbmS.updateOne(
{ "traceId": 676517451 },
{ "$set": { "recipients.$.status": "Sent" } },
{ "multi": true }
)
您有两个选择:
- 单独更新数组recipients的元素(您已经尝试过这个)
- 获取整个文档,对其进行所需的修改,然后替换
关于java - MongoDB 位置运算符 $ 在 java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46527010/