英文:
How to delete a specific array element(array of array) in mongodb
问题
我试图删除数组中特定元素的部分,该元素存在于数组中。这是我的数据:
我想要删除 videoContent _id = x2
我想要更新 videoContent 的 link 为 "x2x",其中 _id=x1
{
"_id" : ObjectId("xxyyxx"),
"name" : "Test",
"subscribed" : [
{
"videoContent" : [
{
"title" : "yyy",
"link" : "xxx",
"_id" : ObjectId("x1")
},
{
"title" : "yyy2",
"link" : "xxx2",
"_id" : ObjectId("x2")
}
],
"webinarContent" : [
{
"title" : "yyy",
"link" : "xxx",
"_id" : ObjectId("y1")
},
{
"title" : "yyy2",
"link" : "xxx2",
"_id" : ObjectId("y2")
}
],
"_id" : ObjectId("4646464")
}
]
}
我来自SQL背景,我不太理解MongoDB中的条件。感谢您的帮助。
英文:
So I am trying to delete a specific element of the array which is present in an array
This is my data
I want to delete videoContent _id = x2
I want to update videoContent link = "x2x" where _id=x1
{
"_id" : ObjectId("xxyyxx"),
"name" : "Test",
"subscribed" : [
{
"videoContent" : [
{
"title" : "yyy",
"link" : "xxx",
"_id" : ObjectId("x1")
},
{
"title" : "yyy2",
"link" : "xxx2",
"_id" : ObjectId("x2")
}
],
"webinarContent" : [
{
"title" : "yyy",
"link" : "xxx",
"_id" : ObjectId("y1")
},
{
"title" : "yyy2",
"link" : "xxx2",
"_id" : ObjectId("y2")
}
],
"_id" : ObjectId("4646464")
}
]
}
I am from a SQL background I can't understand where conditions in mongodb.. TIA
答案1
得分: 0
你可以使用 $pull
从列表中删除一个元素:
db.collection('collection').updateOne(
{ _id: ObjectId('xxyyxx') },
{ $pull: { "subscribed.videoContent._id": ObjectId('x2') }}
);
你可以使用 $set
并搭配 arrayFilters
更新嵌套的双重数组项:
db.collection('collection').updateOne(
{ _id: ObjectId('xxyyxx') },
{ $set: { "subscribed.0.videoContent.$[content].link": 'x2x' }},
{ arrayFilters: [{ 'content._id': ObjectId('x1') }]}
);
英文:
You can use $pull
to delete an element from the list:
db.collection('collection').updateOne(
{ _id: ObjectId("xxyyxx") },
{ $pull: { "subscribed.videoContent._id": ObjectId("x2") }}
);
You can use $set
with arrayFilters
to update a double nested array item:
db.collection('collection').updateOne(
{ _id: ObjectId("xxyyxx") },
{ $set: { "subscribed.0.videoContent.$[content].link": "x2x" }},
{ arrayFilters: [{ 'content._id': ObjectId("x1") }]}
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论