英文:
MongoDB - How to move an array from one array field to another
问题
You can frame your MongoDB query to move the array from the draft field to the publish field using the $pull and $push operators. Here's the query:
db.collection.update(
{ },
{
$pull: {
draft: ["Panic 2", "63d2648d373f7fea3fa9d387_1681628752497"]
},
$push: {
publish: ["Panic 2", "63d2648d373f7fea3fa9d387_1681628752497"]
}
}
)
This query will first use $pull to remove the specified array from the draft field if it exists, and then it will use $push to add the same array to the publish field. This way, you can move the array from draft to publish with only the presence of the ID.
英文:
I have two fields in a MongoDB document publish and draft with schema as:
{
publish: [[
{ type: String, required: true },
{ type: String, required: true }
]],
draft: [[
{ type: String, required: true },
{ type: String, required: true }
]]
}
and value looks like this in DB:
{
"draft": [
[
"Panic 2",
"63d2648d373f7fea3fa9d387_1681628752497"
],
//...
],
"publish": [
[
"Ruins Exploration Gone Wrong!",
"63d2648d373f7fea3fa9d387_1681628787816"
],
[
"Fresh Start",
"63d2648d373f7fea3fa9d387_1681628805269"
],
//...
]
}
Now I'm working on a query that can move the array
["Panic 2","63d2648d373f7fea3fa9d387_1681628752497"]
from draft to publish but I only have 63d2648d373f7fea3fa9d387_1681628752497 to achieve so.
How should I frame my query?
EDIT: I have tried some way and was able to pull the array from draft field but haven't been able to push that array to publish with only the presence of id.
答案1
得分: 1
假设内部数组中的第二个元素是唯一的,您可以使用聚合管道执行更新操作:
-
$setselected- 从draft数组中筛选具有匹配id值的元素。draft- 从draft数组中筛选元素以将其(selected)移除。 -
$setpublished- 将selected数组与published数组合并。selected- 移除selected字段。
英文:
Assume that the second element within the inner array is unique, you can perform the update with aggregation pipeline:
-
$setselected- Filter the matching element for the id value from thedraftarray.draft- Filter the element to remove it (selected) from thedraftarray. -
$setpublished- Combine theselectedarray withpublishedarray.selected- Remove theselectedfield.
db.collection.update({
"draft": {
$elemMatch: {
$elemMatch: {
$eq: "63d2648d373f7fea3fa9d387_1681628752497"
}
}
}
},
[
{
$set: {
selected: {
$filter: {
input: "$draft",
cond: {
$eq: [
{
$arrayElemAt: [
"$$this",
1
]
},
"63d2648d373f7fea3fa9d387_1681628752497"
]
}
}
},
draft: {
$filter: {
input: "$draft",
cond: {
$ne: [
{
$arrayElemAt: [
"$$this",
1
]
},
"63d2648d373f7fea3fa9d387_1681628752497"
]
}
}
}
}
},
{
$set: {
publish: {
$concatArrays: [
"$publish",
"$selected"
]
},
selected: "$$REMOVE"
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论