0

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

kong
  • 1,961
  • 16
  • 16
sagar
  • 143
  • 1
  • 2
  • 11

1 Answers1

0

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

kong
  • 1,961
  • 16
  • 16
  • Hi Kong its not working we are getting error like below:- TypeMismatch Found Required Imports.DBObjects actual String,Import.DBObjects And We Tried Another Way Also:- val removingData = $pull(MongoDBObject("categories.$.subcategories" -> MongoDBObject("subcategoryname" -> "camera"))) but this query not deleting mydata... – sagar Dec 04 '13 at 09:52
  • What version of casbah are you using? I ran the code above on the sample data you pasted and it removed the subcategory as expected with casbah 2.6.3. The only change I made was correcting the spelling of "Electronics" in the categoryname. – kong Dec 04 '13 at 12:11