小编hwi*_*enb的帖子

MongoDB - 如果不满足 arrayFilters,则对数组执行 upsert

我在 mongo 中存储了以下文件:

{
"_id" : ObjectId("5d1a08d2329a3c1374f176df"),
"associateID" : "1234567",
"associatePreferences" : [ 
    {
        "type" : "NOTIFICATION",
        "serviceCode" : "service-code",
        "eventCode" : "test-template",
        "preferences" : [ 
            "TEXT", 
            "EMAIL"
        ]
    }, 
    {
        "type" : "URGENT_NOTIFICATION",
        "serviceCode" : "service-code",
        "eventCode" : "test-template",
        "preferences" : [ 
            "TEXT"
        ]
    }
]
}
Run Code Online (Sandbox Code Playgroud)

我基本上试图根据它的类型、serviceCode 和 eventCode 查询 associatePreferences 数组的元素之一,并向首选项数组添加一个新值。但是,如果类型、serviceCode 和 eventCode 的组合不存在,我想向带有这些值的 associatePreferences 数组添加一个新元素。这是我当前的查询:

db.user_communication_preferences.update(
   {'associateID':'testassociate'}, 
   {$addToSet:{'associatePreferences.$[element].preferences':"NEW_VALUE"}}, 
   {arrayFilters:[{'element.serviceCode':'service-code-not-present', 'element.eventCode':'event-code-not-present','element.type':'URGENT_NOTIFICATION'}]}
)
Run Code Online (Sandbox Code Playgroud)

如果所有 arrayFilters 都存在于 associatePreferences 的元素中,则此查询有效,但如果不存在,则不会添加新元素。我错过了什么?

mongodb mongodb-query

8
推荐指数
1
解决办法
374
查看次数

标签 统计

mongodb ×1

mongodb-query ×1