在同一文档MongoDB中将元素从一个数组移动到另一个数组 [英] Move an element from one array to another within same document MongoDB
问题描述
我有如下数据:
{
"_id": ObjectId("4d525ab2924f0000000022ad"),
"array": [
{ id: 1, other: 23 },
{ id: 2, other: 21 },
{ id: 0, other: 235 },
{ id: 3, other: 765 }
],
"zeroes": []
}
我想从一个数组中拉出一个元素,然后将其$ push到同一文档中的第二个数组中,以产生类似于以下内容的东西:
I'm would like to to $pull an element from one array and $push it to a second array within the same document to result in something that looks like this:
{
"_id": ObjectId("id"),
"array": [
{ id: 1, other: 23 },
{ id: 2, other: 21 },
{ id: 3, other: 765 }
],
"zeroes": [
{ id: 0, other: 235 }
]
}
我意识到我可以通过先查找然后进行更新来做到这一点,
I realize that I can do this by doing a find and then an update, i.e.
db.foo.findOne({"_id": param._id})
.then((doc)=>{
db.foo.update(
{
"_id": param._id
},
{
"$pull": {"array": {id: 0}},
"$push": {"zeroes": {doc.array[2]} }
}
)
})
我想知道是否可以使用原子功能. 像
I was wondering if there's an atomic function that I can do this with. Something like,
db.foo.update({"_id": param._id}, {"$move": [{"array": {id: 0}}, {"zeroes": 1}]}
发现这篇文章慷慨地提供了我使用的数据,但问题在4年后仍未解决.在过去的四年中,是否为此制定了解决方案?
Found this post that generously provided the data I used, but the question remains unsolved after 4 years. Has a solution to this been crafted in the past 4 years?
推荐答案
没有
There is no $move
in MongoDB. That being said, the easiest solution is a 2 phase approach:
- 查询文档
- 使用
$pull
和$push
/这里的重要部分是确保所有内容都是幂等的,它是将原始数组文档包含在更新查询中.The important part here, to make sure everything is idempotent, is to include the original array document in the query for the update.
提供以下格式的文件:
{ _id: "foo", arrayField: [ { a: 1, b: 1 }, { a: 2, b: 1 } ] }
让我们说您想将
{ a: 1, b: 1 }
移到另一个字段(可能称为someOtherArrayField
),您想要做类似的事情.Lets say you want to move
{ a: 1, b: 1 }
to a different field, maybe calledsomeOtherArrayField
, you would want to do something like.var doc = db.col.findOne({_id: "foo"}); var arrayDocToMove = doc.arrayField[0]; db.col.update({_id: "foo", arrayField: { $elemMatch: arrayDocToMove} }, { $pull: { arrayField: arrayDocToMove }, $addToSet: { someOtherArrayField: arrayDocToMove } })
我们使用
$elemMatch
的原因是确保自我们首次查询文档以来,要从数组中删除的字段没有更改.当与$pull
结合使用时,它也不是严格的必要,但在这种情况下,我通常会过分谨慎.如果您的应用程序中没有并行性,而您只有一个应用程序实例,那么就没有严格的必要.The reason we use the
$elemMatch
is to be sure the field we are about to remove from the array hasn't changed since we first queried the document. When coupled with a$pull
it also isn't strictly necessary, but I am typically overly cautious in these situations. If there is no parallelism in your application, and you only have one application instance, it isn't strictly necessary.现在,当我们检查生成的文档时,我们得到:
Now when we check the resulting document, we get:
db.col.findOne() { "_id" : "foo", "arrayField" : [ { "a" : 2, "b" : 1 } ], "someOtherArrayField" : [ { "a" : 1, "b" : 1 } ] }
这篇关于在同一文档MongoDB中将元素从一个数组移动到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!