Daniel Lawton
Daniel Lawton

Reputation: 466

Remove final element of array in MongoID document - Rails

I've been trying to remove the final element of an array in a MongoID document, but I am struggling for some unknown reason.

We have a document in MongoDB:

{
    "_id" : ObjectId("606c774ff34c295ec7ac5eb7"),
    "child_table" : [ 
        {
            "_id" : ObjectId("606c7768f34c291171ac5ec2"),
            "string3" : "y"
        },
        {
            "_id" : ObjectId("606c7768f34c291171ac5ef6"),
            "string3" : "u"
        }
    ]
}

This document is contained within record.

record = Record.find_by(:id=> "606c774ff34c295ec7ac5eb7")

I can delete the second element, which I'm doing with:

record.child_table.delete_at(record.child_table.count-1)

This works fine, the second element of the array child_table is deleted. All right. However, when I go to delete the final element in the array, the code runs with no errors, but I go to check the document in Mongo and it is still showing the final element.

I have also tried running:

self.unset(:child_table)

But this has not done anything for me.

Please let me know any suggestions! Thanks

Upvotes: 3

Views: 393

Answers (2)

Use $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.

Demo with only 1 child element - https://mongoplayground.net/p/eGLqEPUjUAV

Demo with 2 child elements - https://mongoplayground.net/p/nxXBaqK-3RL

db.collection.update(
    { _id: ObjectId("606c774ff34c295ec7ac5eb7") },
    { $pop: { child_table: 1 } } // removes last element from the array
)

Upvotes: 3

Programmer Analyst
Programmer Analyst

Reputation: 919

please refer to https://stackoverflow.com/a/4588909/6462538

trick here is to first unset last element in array and then pull that element. Considering our collection is users below commands will remove the last element of array

var record= db.users.find({ _id: ObjectId("606c774ff34c295ec7ac5eb7") }).toArray();

var index= record[0].child_table.length-1;
var unsetelement = "child_table."+index;
unsetelement = unsetelement.toString();

db.users.update({ _id: ObjectId("606c774ff34c295ec7ac5eb7") }, {$unset : { unsetelement : 1 }}) 
db.users.update({ _id: ObjectId("606c774ff34c295ec7ac5eb7") }, {$pull : {"child_table" : null}})

Upvotes: 1

Related Questions