[英]How to Delete a Specific Object From The Arrayof Objects in MongoDB Casbah
mydata is look like below:- mydata如下所示:-
{
"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 电子类别中的子类别(例如:-我要从mydata中删除相机对象)
Expected Output:-(after deleting the camera Object) 预期输出:-(删除相机对象后)
{
"categories": [
{
"categoryname": "Eletronics",
"categoryId": "89sxop",
"displayname": "Eletronics",
"subcategories": [
{
"subcategoryname": "laptop",
"subcategoryId": "454",
"displayname": "Laptop"
}
]
}
]
}
Best Regards GSY 最好的问候GSY
You need to use the $pull
operator, specifying the subcategories
array and the condition used to pick the elements to remove. 您需要使用$pull
运算符,指定subcategories
数组以及用于选择要删除的元素的条件。 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. $
运算符可用于选择您感兴趣的特定categories
元素的subcategories
数组。有关详细信息,请参见mongo的Update Array Operators文档。 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 subcategoryname
s 如果要删除多个子类别,可以使用$or
运算符指定多个subcategoryname
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.