mongoDB从数组中删除 [英] mongoDB delete from array
问题描述
我想知道如何从mongoDB中的数组中删除某些元素.
我将以下json保存在集合geojsons
中:
I am wondering how I can delete certain elements from an array in mongoDB.
I have the following json saved in the collection geojsons
:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"ID": "1753242",
"TYPE": "8003"
}
},
{
"type": "Feature",
"properties": {
"ID": "4823034",
"TYPE": "7005"
}
},
{
"type": "Feature",
"properties": {
"ID": "4823034",
"TYPE": "8003"
}
}
]
}
我想删除数组features
中的每个元素,其中properties.TYPE
等于8003
.
我使用以下语句尝试了此操作,但它并未删除任何内容.
And I want to delete every element in the array features
, where properties.TYPE
equals 8003
.
I tried it with the following statement, but it does not delete anything.
db.geojsons.aggregate([
{$match: {'features': {$elemMatch : {"properties.TYPE": '8003' }}}},
{$project: {
features: {$filter: {
input: '$features',
as: 'feature',
cond: {$eq: ['$$feature.properties.TYPE', '8003']}
}}
}}
])
.forEach(function(doc) {
doc.features.forEach(function(feature) {
db.collection.deleteOne(
{ "feature.properties.TYPE": "8003" }
);
print( "in ")
});
});
有人知道,为什么这不删除任何内容,或者如何删除匹配的元素?
对我来说,故障似乎在forEach
内部,因为print语句已按预期执行.
Does anybody know, why this does not delete anything or how to delete the matching elements?
For me it seems that the failure is inside the forEach
, since the print statement gets executed as expected.
推荐答案
此处无需aggregation
,您可以使用 $ pull " rel ="nofollow noreferrer" >更新
No need of aggregation
here, you can use $pull of update
db.geojsons.update(
{ "type": "FeatureCollection" }, //or any matching criteria
{$pull: { "features": { "properties.TYPE": "8003"} }}
);
这篇关于mongoDB从数组中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!