I'm trying to find a way to update a single array item using mongoid. I'm using Rails 4 and Mongodb.
My model looks like this
class User
include Mongoid::Document
include Mongoid::Timestamps
field :my_book_list, type: Array, default: []
field :book_name, type: String
I'm able to add entry to the array field using the following code:
User.where(id: self.user_id).add_to_set("my_book_list" => self.book_name)
After I have added data to the array, in the database it looks like this
db.collection.users
{
"_id" : ObjectId("56e09d54a0d00b0528000001"),
"status" : true,
"sign_in_count" : 3,
"my_book_list" :
["Learning Ruby", "MongoDB for Dummies"]
}
What I'm struggling with is to find a Rails / Mongoid way of updating the value of an item in the array by looking for the name.
Simply put, how do I change the value of my_book_list[1] by searching for it through name and not knowing its index. In this case index 1 is "MongoDB for Dummies" and needs to be updated to "MongoDB". So that the "my_book_list" array field looks like this after its updated:
db.collection.users
{
"_id" : ObjectId("56e09d54a0d00b0528000001"),
"status" : true,
"sign_in_count" : 3,
"my_book_list" :
["Learning Ruby", "MongoDB"]
}
How do I achieve this ?
{ "_id": ObjectId("56e09d54a0d00b0528000001"), "my_book_list": { "$ne": "Leaning Ruby" } },{ "$push": { "my_book_list": "Learning Ruby" } }, with the differnce being that not only is the element not added where it already exists, but it does so because the condition that it does not exist does not match anything to update. That's the distinction, but it's really unclear what you actually need or why the$addToSetused does not suit your purpose.