我们假设这是我的数据:
{
"_id" : ObjectId("52892936b996cc760d000002"),
"created_at" : ISODate("2013-11-17T20:38:14.248Z"),
"name" : "Two",
"subcategories" : [
{
"subcategory" : "Alpha",
"products" : [
{
"name" : "Product 5",
"primary_price" : "2",
"secondary_price" : "3",
"created_at" : "Sun Nov 17 2013 20:39:20 GMT+0000 (GMT)"
},
{
"name" : "Product 7",
"primary_price" : "2",
"secondary_price" : "3",
"created_at" : "Sun Nov 17 2013 20:39:31 GMT+0000 (GMT)"
}
]
},
{
"subcategory" : "Bravo",
"products" : [
{
"name" : "Product 6",
"primary_price" : "2",
"secondary_price" : "3",
"created_at" : "Sun Nov 17 2013 20:39:26 GMT+0000 (GMT)"
},
{
"name" : "Product 8",
"primary_price" : "2",
"secondary_price" : "3",
"created_at" : "Sun Nov 17 2013 20:39:38 GMT+0000 (GMT)"
},
{
"name" : "Apple",
"primary_price" : "5",
"secondary_price" : "13",
"created_at" : "Sat Nov 23 2013 12:00:18 GMT+0000 (GMT)"
},
{
"name" : "Lemon",
"primary_price" : "9",
"secondary_price" : "13",
"created_at" : "Sat Nov 23 2013 12:00:32 GMT+0000 (GMT)"
}
]
}
]
}
我想删除“产品5”如何使用mongo进行操作(希望无需循环和/或进行任何数据转换?
我尝试过这里描述的方法:how to delete a specific object from array object in MongoDB
此处Deleting a single object from an array of objects in MongoDB
和Mongodb update operation inside sub array
我假设它不起作用的原因是因为我的对象是双嵌套的。我一直试图找到一个解决方案,我提出的涉及数据操作,我宁愿避免。
非常感谢帮助/建议。
答案 0 :(得分:2)
您链接的第一个问题基本上是同一个问题。我不确定你尝试了什么,但是这会起作用(在shell中):
db.test.update(
{
"_id" : ObjectId("52892936b996cc760d000002"),
'subcategories.subcategory': 'Alpha'
},
{$pull: {'subcategories.$.products': {name: 'Product 5'}}})
查询对象通过subcategory
运算符标识要$pull
products
上的$
元素。