java - MongoDB 位置运算符 $ 在 java 中不起作用

标签 java mongodb spring-boot

我在 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/

相关文章:

javafx - 对话框关闭时取消任务

java - 在 Android 中使用命名空间常量的接口(interface)

c# - MongoDB $geoIntersects 没有在多边形中找到一条完全包含的线,但找到了另一条

postgresql - 无法从 wsl 2 上运行的服务之一连接到 wsl 2 上的容器中运行的 postgres 数据库

java - 如何更改 Apache Tomcat 默认错误页面值?

java - 调试 'Detail Formatters' 如何解析 eclipse 中的类?

java - Paint() try-catch 语句不会执行访问文件的函数

mongodb - 如何使用 Meteor 在客户端查看 Minimongo 数据库的内容?

javascript - 了解 Mongoose 子文档

java - JPA 调用 MSSQL 存储过程返回重复记录