arrays - 删除 MongoID 文档中数组的最后一个元素 - Rails

标签 arrays ruby-on-rails mongodb mongoid

我一直在尝试删除 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/

相关文章:

javascript - 对象已排序,但未使用 lodash sortBy 保留其键

ruby-on-rails - 如何在电子邮件中附加动态文件内容

ruby-on-rails - ruby on rails 的语法错误

ruby-on-rails - 使用 Devise/Rails 4/Minitest 运行 Controller 测试时无法登录

javascript - 我应该如何使用 node.js 和 Mongodb 在 Javascript 中实现异步函数?

c++ - 将 const char* 类型转换为 int 数组

mongodb - Mongodb 在隐式 AND 中发现方法混淆

java - 是什么导致我的二维数组发生变化?

javascript - 鉴于它是动态生成的,我如何在 Javascript/jQuery 中访问此 JSON 数据?

c - 指针歧义