简体   繁体   中英

Remove object in nested array mongodb

I have somwthing like the next json in mongo.

My objective is to delete all nested objects with "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"
        }
      ]
    }
  ]
}

Expected 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"
        }
      ]
    }
  ]
}

This will give you documents where id_s: 2 and ignore rest of them.

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
}

);

Output:

  /* 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"
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM