在MongoDB中$ unwind之后,$ match并更新对象中的特定键 [英] $match and update a certain key in object after $unwind in MongoDB

查看:596
本文介绍了在MongoDB中$ unwind之后,$ match并更新对象中的特定键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似以下文件的文件:

I have documents like the following one:

{ 
    "_id" : ObjectId("5dc027d38da295b969eca67c"), 
    "emp_no" : 10031, 
    "salaries" : [
        {
            "salary" : 40000, 
            "from_date" : "1991-09-01", 
            "to_date" : "1992-08-31"
        }, 
        {
            "salary" : 40859, 
            "from_date" : "1992-08-31", 
            "to_date" : "1993-08-31"
        }, 
        {
            "salary" : 41881, 
            "from_date" : "1993-08-31", 
            "to_date" : "1994-08-31"
        }
    ]
}

作为一个目标,我需要为每个范围在 1985-01-01 - 1985-12-31 .
到目前为止,我想到了以下查询:

As a goal I need to increment salary by 1000 for every object that has from_date key in a range of 1985-01-01 - 1985-12-31.
So far i came up with this query:

db.emp_salaries.aggregate( [
  { $unwind: "$salaries" },
  { $match: {
    "salaries.from_date": {$gte: "1985-01-01"},
    "salaries.from_date": {$lte: "1985-12-13"},
  } }
] )

但是我不能以此方式定位from_date键.我不知道该怎么做.该$match似乎被完全忽略了.我听说过一个运算符,它可以从目标的开头自动定位此类键,而不管其位置如何,但是找不到它.
如何定位此键并在salary上执行更新?

but i can't target from_date key this way. I have no idea how to do this. This $match seems to be totally ignored. I've heard about an operator which can automatically target such a key regardless of its position from the beginning of an object, but couldn't find it back.
How do I target this key and perform an update on salary?

推荐答案

过滤后的位置运算符 $[<identifier>]标识与 update操作的arrayFilters条件匹配的数组元素.以下查询将使用匹配条件更新数组中的子文档字段.

The filtered positional operator $[<identifier>] identifies the array elements that match the arrayFilters conditions for an update operation. The following query will update the sub-document fields in the array with the matching condition.

db.arr_upd.updateMany(
    { },
    { $inc: { "salaries.$[elem].salary" : 1000 } },
    { arrayFilters: [ { $and: [ { "elem.from_date": { $gte: "1991-09-01" } },  { "elem.from_date": { $lte: "1992-08-31" } } ] } ] }
)

这会将前两个元素的salary值分别更新为4100041859(对于问题中显示的示例文档).

This will update the first two elements' salary values to 41000 and 41859, respectively (for the example document shown in the question post).

这篇关于在MongoDB中$ unwind之后,$ match并更新对象中的特定键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆