【问题标题】:MongoDB - Increment Nested Array of Documents Where Not Null [duplicate]MongoDB - 增加不为空的嵌套文档数组[重复]
【发布时间】:2018-10-20 01:26:27
【问题描述】:

我有以下示例文档结构:

{
    "_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"
}

感谢您的指导!

【问题讨论】:

  • 听起来你需要聚合。到目前为止,您尝试过哪些命令?你也应该发布这些。

标签: arrays mongodb increment embedded-database documents


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-08-31
    • 1970-01-01
    • 2015-06-04
    • 2021-05-01
    • 2019-05-27
    • 2018-02-18
    • 2018-11-24
    • 1970-01-01
    • 2013-03-19
    相关资源
    最近更新 更多