Mongodb simple update does not work in Ruby/Mongoid - ruby

I have the following MongoDB update operation, but it doesnt seem to work, anyone know why?
User.collection.update({ _id: BSON::ObjectId("5018ed448712ff240e0000a0") },
{ "$set" => { name: "ben" } })
It does not throw an error, but just some integer which I am guessing is the doc size.
I am using Mongoid 2.4.10/Rails 3.2.7

If you are using Mongoid, you coule just do a find and update:
User.find("5018ed448712ff240e0000a0").update_attributes!(name: "ben")
or you could use set:
User.find("5018ed448712ff240e0000a0").set(:name, "ben")
Note that set() takes 2 arguments; it does not accept a hash as an argument

Can you use mongoid API instead and use following command:
User.find("5018ed448712ff240e0000a0").set(name: "ben")

Related

RethinkDB filter and retrieve value from nested array

Using the following query:
r.db('somedb').table('sometable')('users')
I get the following data from the result:
[
   [
      {
         "fn": "dpw",
         "u": "usertwo"
      },
      {
         "fn": "dwd",
         "u": "userone"
      }
   ]
]
I would like to take the field "u" and specify lets say "usertwo" and get the value of "fn" for that "u". I want to have the result filtered using ReQL so that I am not just parsing the json result in nodejs as the result will be enormous eventually. What would be the best and most efficient approach. I am new to RethinkDB and would appreciate if you could explain the answer as best you can.
I'm not sure of what you exactly want, but from my understanding, this is what you are looking for:
r.db('somedb').table('sometable')('users').filter(function(user) {
return user("u").eq("usertwo")
})("fn")
You seem to have an array of array of users. if that was not a typo, the query should probably be
r.db('somedb').table('sometable')('users').nth(0).filter(function(user) {
return user("u").eq("usertwo")
})("fn")

How to use Tire for "MoreLikeThis" query of ElasticSearch

I would like execute this exemple :
$ curl -XGET 'http://localhost:9200/twitter/tweet/1/_mlt?mlt_fields=tag,content&min_doc_freq=1'
with Tire gem. It's poossible ?
My goal to search document related to another document.
It is not implemented directly in tire. Karmi, however, has implemented it as a tire extension in the tire-contrib repository.
Source Code: more_like_this.rb
Add by adding gem 'tire-contrib'
more_like_this_field(:tag, like_text, options = {min_doc_freq: 1})
Okay the internet forgot to include a single example of this call (including the source project), so here is one style of it.
related_articles = Article.search {
query {
more_like_this("#{current_article.title} #{current_article.body}",
fields: [:title, :description],
percent_terms_to_match: 0.1,
min_term_freq: 1,
min_doc_freq: 1
)
}
}
puts related_articles.results.count
puts related_articles.results.first.title if related_articles.present?
The gotcha here are the min_term_freq and min_doc_freq params above. They default to 2 and 5 respectively in ElasticSearch, which makes it easy to get confused while testing this.

Full text search using Mongoid

Is there a way to use MongoDB (v 2.4)'s full text search feature via Mongoid? I tried the answer from google group link but kept on getting the following error.
In one tab, I started mongod as such: ~$ mongod --setParameter textSearchEnabled=true
The line that caused the error:
Article.mongo_session.command({:text => {:search => 'Ruby'}})
It would be great if someone could point out a way to execute MongoDB runCommand within Ruby, so that I could directly run the command db.collection.runCommand( "text", { search: <string> })
failed with error 13111: "exception: wrong type for field (text) 3 != 2"
See https://github.com/mongodb/mongo/blob/master/docs/errors.md
for details about this error.
For anyone finding this, Mongoid 4.0 allows for full text search like this:
Model.text_search('query')
You can chain as you normally would:
Listings.in(category: sections).where(listing_type: 'Website').text_search(params[:q]).to_a
Indexes are pretty easy as well:
index({name: "text", description: "text"}, {weights: {name: 10, description: 2}, name: "TextIndex"})
EDIT: July 2017
As reported below, text_search is deprecated. I've been using where() like this:
Model.where('$text' => { '$search' => "\"#{params[:q]}\"" })
I've just tried mongo 2.4 text search via mongoid and bumped into the same issue as you. I've played a little bit with it and found the following solution. Here is how I've made it working
Example:
User.mongo_session.command(text: 'users', search: 'search string')
Here 'text' key should point to the collection name.
You will get Moped::BSON::Document that have information about found documents.
Hope it will help you as well
Based on Durran Jordan answer on a question about 'Mongo 2.4 full text search with Moped?' in this link: https://groups.google.com/forum/?fromgroups=#!topic/mongoid/hJRbaNMy6w4, I will suggest you change your command from:
Article.mongo_session.command({:text => {:search => 'Ruby'}})
to this:
Article.with(database: "text").mongo_session.command({:text => {:search => 'Ruby'}})
For me this one worked.
Here
Favorite.mongo_session.command(:text =>'table_name', search: 'search parameter')
Make sure the :text 's value is the table name and not the field.

Mongodb and Ruby gem - Check if record exists

I've a simple Ruby script (no rails, sinatra etc.) that uses the Mongo gem to insert records into my DB as part of a Redis/Resque worker.
Upon occasion instead of doing a fresh insert I'd like to update a counter field on an existing record. I can do this handily enough with rails/mysql. What's the quickest way of doing this in pure Ruby with Mongodb?
Thanks,
Ed
The Ruby client library for MongoDB is very convenient and easy to use. So, to update a document in MongoDB, use something similar to this:
#!/usr/bin/ruby
require 'mongo'
database = Mongo::Connection.new.db("yourdatabasename")
# get the document
x = database.find({"_id" => "12312132"})
# change the document
x["count"] = (x["count"] || 0) + 1
# update it in mongodb
database["collection"].update("_id" => "thecollectionid", x)
You might want to check out the manual for updating documents in MongoDB as well.
thanks to envu's direction I went with upsert in the end. here is an example snippet of how to use it the Ruby client:
link_id = #globallinks.update(
{
":url" => "http://somevalue.com"
},
{
'$inc' => {":totalcount" => 1},
'$set' => {":timelastseen" => Time.now}
},
{
:upsert=>true
}
)

Find documents including element in Array field with mongomapper?

I am new to mongodb/mongomapper and can't find an answer to this.
I have a mongomapper class with the following fields
key :author_id, Integer
key :partecipant_ids, Array
Let's say I have a "record" with the following attributes:
{ :author_id => 10, :partecipant_ids => [10,15,201] }
I want to retrieve all the objects where the partecipant with id 15 is involved.
I did not find any mention in the documentation.
The strange thing is that previously I was doing this query
MessageThread.where :partecipant_ids => [15]
which worked, but after (maybe) some change in the gem/mongodb version it stopped working.
Unfortunately I don't know which version of mongodb and mongomapper I was using before.
In the current versions of MongoMapper, this will work:
MessageThread.where(:partecipant_ids => 15)
And this should work as well...
MessageThread.where(:partecipant_ids => [15])
...because plucky autoexpands that to:
MessageThread.where(:partecipant_ids => { :$in => [15] })
(see https://github.com/jnunemaker/plucky/blob/master/lib/plucky/criteria_hash.rb#L121)
I'd say take a look at your data and try out queries in the Mongo console to make sure you have a working query. MongoDB queries translate directly to MM queries except for the above (and a few other minor) caveats. See http://www.mongodb.org/display/DOCS/Querying

Resources