我一直在尝试删除 MongoID 文档中数组的最后一个元素,但由于某些未知原因我一直在努力。
我们在 MongoDB 中有一个文档:
{
"_id" : ObjectId("606c774ff34c295ec7ac5eb7"),
"child_table" : [
{
"_id" : ObjectId("606c7768f34c291171ac5ec2"),
"string3" : "y"
},
{
"_id" : ObjectId("606c7768f34c291171ac5ef6"),
"string3" : "u"
}
]
}
此文档包含在 record
中。
record = Record.find_by(:id=> "606c774ff34c295ec7ac5eb7")
我可以删除第二个元素,我正在这样做:
record.child_table.delete_at(record.child_table.count-1)
这很好用,数组 child_table
的第二个元素被删除了。好的。
然而,当我去删除数组中的最后一个元素时,代码运行没有错误,但我去检查 Mongo 中的文档,它仍然显示最后一个元素。
我也试过运行:
self.unset(:child_table)
但这对我没有任何帮助。
请让我知道任何建议! 谢谢
最佳答案
使用$pop
The $pop operator removes the first or last element of an array. Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array.
只有 1 个子元素的演示 - https://mongoplayground.net/p/eGLqEPUjUAV
具有 2 个子元素的演示 - https://mongoplayground.net/p/nxXBaqK-3RL
db.collection.update(
{ _id: ObjectId("606c774ff34c295ec7ac5eb7") },
{ $pop: { child_table: 1 } } // removes last element from the array
)
关于arrays - 删除 MongoID 文档中数组的最后一个元素 - Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66971994/