MongoDB - 增加不为空的嵌套文档数组

MongoDB - Increment Nested Array of Documents Where Not Null

我有以下示例文档结构:

{
    "_id" : 1,
    "distributor" : "Jackson",
    "systems" : [
        {
            "name" : "XBOX",
            "quantity" : null,
        },
        {
            "name" : "PlayStation",
            "quantity" : 10,
        },
        {
            "name" : "Nintendo",
            "quantity" : 20,
        },
        {
            "name" : "Atari",
            "quantity" : null,
        },
    ],
    "games" : [
        {
            "name" : "Call of Duty",
            "quantity" : 5
        },
        {
            "name" : "Super Mario Bros",
            "quantity" : null,
        },
        {
            "name" : "Madden",
            "quantity" : 4,
    ],
    "comments" : null,
    "contact" : "Bill"
}

我想将每个 NOT NULL 嵌入文档的数量增加 1。到目前为止,我能够让它更新第一个发现的非空条目(在本例中为 Playstation),但没有别的。

我想要的结果是这样的:

{
    "_id" : 1,
    "distributor" : "Jackson",
    "systems" : [
        {
            "name" : "XBOX",
            "quantity" : null,
        },
        {
            "name" : "{PlayStation}",
            "quantity" : 11,
        },
        {
            "name" : "Nintendo",
            "quantity" : 21,
        },
        {
            "name" : "Atari",
            "quantity" : null,
        },
    ],
    "games" : [
        {
            "name" : "Call of Duty",
            "quantity" : 6
        },
        {
            "name" : "Super Mario Bros",
            "quantity" : null,
        },
        {
            "name" : "Madden",
            "quantity" : 5,
    ],
    "comments" : null,
    "contact" : "Bill"
}

感谢您的指导!

如果您使用的是 MongoDB 3.6 或更高版本,您可以使用 arrayFilters

db.col.update(
   {_id: 1},
   { $inc: { "systems.$[elem].quantity": 1, "games.$[elem].quantity": 1 } },
   { arrayFilters: [ { "elem.quantity": { $ne: null } }  ] });

数组过滤器只是将您的条件应用于数组的每个元素,并在该特定元素匹配时执行您的更新。