How to Delete a Specific Object From The Arrayof Objects in MongoDB Casbah

367 views Asked by At

mydata is look like below:-

    {
    "categories": [
    {
        "categoryname": "Eletronics",
        "categoryId": "89sxop",
        "displayname": "Eletronics",
        "subcategories": [
            {
                "subcategoryname": "laptop",
                "subcategoryId": "454",
                "displayname": "Laptop"
            },
            {
                "subcategoryname": "camera",
                "subcategoryId": "sony123",
                "displayname": "Camera"
            }
        ]
      }
      ]
      }

I want to delete a specific object from a Subcategories Array

we are Trying like below code:-(This is to Delete Category)

val removingData = $pull(MongoDBObject("categories" -> MongoDBObject("categoryName" -> "Entertainment")))

this code is for removing Particular category.

But I Want To Remove ONE or MORE subCategories from particular category. The subCategory(Ex:-i want to Delete camera Object from mydata) from the Electronics category

Expected Output:-(after deleting the camera Object)

{
"categories": [
    {
        "categoryname": "Eletronics",
        "categoryId": "89sxop",
        "displayname": "Eletronics",
        "subcategories": [
            {
                "subcategoryname": "laptop",
                "subcategoryId": "454",
                "displayname": "Laptop"
            }

        ]
    }
]
}

Best Regards GSY

1

There are 1 answers

2
kong On BEST ANSWER

You need to use the $pull operator, specifying the subcategories array and the condition used to pick the elements to remove. The $ operator can be used to select the subcategories array of the specific categories element you're interested in. See the Update Array Operators docs of mongo for details. Something like the following should work:

val query = MongoDBObject("categories.categoryname" -> "Electronics")
val removingData = $pull("categories.$.subcategories" -> MongoDBObject("subcategoryname" -> "camera"))

collection.update(query, removingData)

If you want to remove multiple subcategories, you can use the $or operator to specify multiple subcategorynames