【问题标题】:Remove object in nested array mongodb删除嵌套数组 mongodb 中的对象
【发布时间】:2021-07-03 01:29:40
【问题描述】:

我有类似 mongo 中的下一个 json 的东西。

我的目标是用"id_s": "1"删除所有嵌套对象

{
  "_id": "5150a1199fac0e6910000002",
  "name": "some name",
  "p_a": [
    {
      "sub_name": "subname"
    },
    {
      "sub_name": "subname2",
      "p_p": [
        {
          "last_level": "toDelete",
          "id_s": "1"
        },
        {
          "last_level": "toKeep",
          "id_s": "2"
        }
      ]
    },
    {
      "sub_name": "subname3",
      "p_p": [
        {
          "last_level": "toDelete",
          "id_s": "1"
        },
        {
          "last_level": "toKeep",
          "id_s": "2"
        }
      ]
    }
  ]
}

预期的 JSON:

{
  "_id": "5150a1199fac0e6910000002",
  "name": "some name",
  "p_a": [
    {
      "sub_name": "subname"
    },
    {
      "sub_name": "subname2",
      "p_p": [
        {
          "last_level": "toKeep",
          "id_s": "2"
        }
      ]
    },
    {
      "sub_name": "subname3",
      "p_p": [
        {
          "last_level": "toKeep",
          "id_s": "2"
        }
      ]
    }
  ]
}

【问题讨论】:

  • 你能粘贴你预期的输出吗?
  • 是的,当然。我把它粘贴在正文问题中
  • 您希望在数据库中删除它吗?或者只是输出应该忽略匹配id_s: 1的文档?
  • 我想被删除,但我也很好奇如何获得忽略匹配条件的输出

标签: arrays json mongodb


【解决方案1】:

这将为您提供id_s: 2 所在的文档并忽略其余部分。

db.getCollection("test").aggregate(
[
    { 
        "$match" : { 
            "_id" : ObjectId("5150a1199fac0e6910000002")
        }
    }, 
    { 
        "$unwind" : { 
            "path" : "$p_a"
        }
    }, 
    { 
        "$unwind" : { 
            "path" : "$p_a.p_p"
        }
    }, 
    { 
        "$match" : { 
            "p_a.p_p.id_s" : "2"
        }
    }
], 
{ 
    "allowDiskUse" : false
}

);

输出:

  /* 1 */
{
    "_id" : ObjectId("606d83fe44c9fc09f60d0756"),
    "name" : "some name",
    "p_a" : {
        "sub_name" : "subname2",
        "p_p" : {
            "last_level" : "toKeep",
            "id_s" : "2"
        }
    }
}

/* 2 */
{
    "_id" : ObjectId("606d83fe44c9fc09f60d0756"),
    "name" : "some name",
    "p_a" : {
        "sub_name" : "subname3",
        "p_p" : {
            "last_level" : "toKeep",
            "id_s" : "2"
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多