Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pushing item in mongoid array

I have a model defined like this :

class Foo
  include ::Mongoid::Document

  field :name, type: String
  field :followed_bars, type: Array
  field :favorite_bars, type: Array
end

I created a Foo object like this :

foo = Foo.new(name: "Test")
foo.save

In my DB when I type db.foo.find() I can see the object I just created. Then, in my application I'm trying to do this :

foo = Foo.first
foo.push(:followed_bars, "hello")

And every time I'm getting an error : ArgumentError: wrong number of arguments (2 for 1)

I'm not sure to understand what am I missing here ?

Thanks in advance for help !

Regards.

like image 767
Hito Avatar asked Sep 08 '13 11:09

Hito


People also ask

How do I push an array object in MongoDB?

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.

How do you update an array element in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

How do I pull an element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


1 Answers

I just found how to do a push on a mongoid array.

In the API documentation they give an example (mongoid 3.x) :

Model#push    person.push(:aliases, "007")

I'm using mongoid 4.0.0 and they changed the method definition, now we have to use the new syntax so I had to write :

foo.push(aliases: "test")

Problem solved so.

like image 119
Hito Avatar answered Sep 28 '22 19:09

Hito