Mongoid where clause ruby hash - ruby

Say I have a mongoid document which has a field :pairs with the type of hash. When I wan't to query on the hash like this:
Doc.where(:pairs=>{"field1"=>1})
I get results back because I have in pairs a field with value one. I also have values for more than 1. When I do the following, nil is returned:
Doc.where(:pairs=>{"field1"=>{"$gt"=>0}})
This doesn't seem to work, and I do have pairs with key field1 and values bigger than 0. Can anyone provide me info on why this doesn't work?

Just try: Dco.where(:pairs.gt => 0)
For more detail mongoid querying see following link.
http://mongoid.org/en/mongoid/docs/querying.html

Doc.where('pairs.field1' => {"$gt"=>1})

Related

How do you explicitly find a record where a field is NULL?

From the documentation:
When query with struct, GORM will only query with those fields has non-zero value, that means if your field’s value is 0, '', false or other zero values, it won’t be used to build query conditions.
Here is an example of what I am trying to do :
type Dog struct {
ID uuid.UUID
OwnerID *uuid.UUID
}
The owner ID pointer may be nil.
db.Where("owner_id", nil).Find(&dogs)
But that returns all dogs (I expected this from the doc). I tried doing:
db.Where("owner_id", "NULL").Find(&dogs)
But that returns an empty list.
Is there a way to explicitly search for a NULL value field?
According to the docs, this should work:
db.Where("owner_id IS NULL").Find(&dogs)
Yeah, if you want to get the data with the value is null. You only have some choices.
use map interface
use struct with conditions
db.Where("owner_id IS NULL").Find(&dogs)
// or you can also try different way of writing
db.Find(&dogs, "owner_id IS NULL")
You were close in your original attempt. You can also achieve your desired result by writing the query as below.
db.Where("owner_id = ?", "NULL").Find(&dogs)

How to solve AmbiguousColumn error in postgresql with ruby project

I would like to join two query result.
First one is
Gig.where(id:gigsInRadioIDS)
When I convert result to json I get this result
[{"id":1,"address":"test1"},{"id":2,"address":"test2"}
Second is.
Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate))
when I convert result to json I get this result
[{"id":15,"status":"available","gig_id":1}]
What I want is to inner join to result
so I hope to get this result(I abbreviated some non related snippet)
[{"id":15,"status":"available","gig_id":1,"id":1,"address":"test1"}]
What I have tried is
Gig.where(id:gigsInRadioIDS).as(:tb_gig).join(Slot.where(status:"available").where(Sequel.lit('("from" > ?) AND ("to" < ?)', fromdate, todate)), gig_id: :id)
And I got this error
Sequel::DatabaseError - PG::AmbiguousColumn: ERROR: column reference "id" is ambiguous
LINE 1: ...) AS "t1" ON ("t1"."gig_id" = "gigs"."id") WHERE ("id" IN (2...
Thanks for reading this complex code.
Any news will be big help. Thanks.
There are a bunch of ways to approach it. It looks like you are querying Slots with some Gigs data mixed in, so you may want to start with your Slot model. The regular join syntax is a little easier to understand and makes it easier to select columns from both tables (i.e. instead of WHERE fk IN (..)). As a bonus, you can mix your gig_id filter into the JOIN clause. Finally, you don't need to use Sequel.lit to do greater than / less than in your WHERE clause, and you should be explicit about the columns you want to select.
Here's how I would write it:
Slot.join(:gigs, [[:id, :gig_id], [:id, gigsInRadioIDS]])
.where(status: 'available') { (from() > fromdate) & (to() < todate) }
.select(Sequel[:slots][:id].as(:slot_id), :status, :gig_id, :address)
Getting .all of the records and outputting JSON should yield something like:
[{"slot_id":15,"status":"available","gig_id":1,"address":"test1"}]
Note the Sequel[:table_name][:column_name] syntax. This is the new style of fully-qualifying identifiers in Sequel 4.49+. (In past versions of Sequel, it would have been written like :table_name__column_name, but that syntax is now deprecated.)
Your where(id:gigsInRadioIDS) translates into WHERE ("id" IN (...)), and since both gigs and slots have an "id" column, the database doesn't know which id you want.
You need to explicitly specify the table with where{{gigs[:id] => gigsInRadioIDS}}
Querying with Sequel

Mongoid "find" returns nil, when "find_by" retrieves record

I'm using Mongoid to access a MongoDB database, however I'm running into an odd problem. It seems like I can only query for records using find_by, as find will always return nil:
invoices = Invoice.find({})
p "invoices"
p invoices
puts ''
invoice = Invoice.find_by({ _id: <ObjectId> })
p "invoice"
p invoice
puts ''
The second query using find_by will return a single record. According to the documentation, find should be returning every record that satisfies the query.
Does anyone have an idea what could be causing this?
Be careful not to confuse the Moped syntax with the Mongoid syntax. For Mongoid, the docs describe the find method:
Find a document or multiple documents by their ids. Will raise an error by default if any of the ids do not match
If you really want every record, Invoice.all can do the trick. (Also be careful with your find_by method. The Mongoid syntax varies from mongo's a bit, so you don't have to have the curlies around your params.)

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")

Compare string ID to BSON::ObjectId

I have an array of made up of type BSON::ObjectId and I want it to compare against some IDs as strings.
if my_array_of_BSON_ObjectIds.include?(#my_id_as_a_string)
# delete the item from the array
else
# add the item to the array as a BSON::ObjectId
end
This is not working as the types are different, can I turn my string into a BSON::ObjectId? If so, how?
Mongoid 2.x with 10gen's driver:
BSON::ObjectId.new('506144650ed4c08d84000001')
Mongoid 3 with moped:
Moped::BSON::ObjectId.from_string('506144650ed4c08d84000001')
Mongoid 4 (moped) / Mongoid 5/6/7 (mongo):
BSON::ObjectId.from_string('506144650ed4c08d84000001')
You can use BSON::ObjectId(#my_id_as_a_string) for representation your id as BSON::ObjectId
refs http://api.mongodb.org/ruby/current/BSON.html#ObjectId-class_method
collection.delete_one({"_id"=>BSON::ObjectId(params['id'])})
This worked for me and it deleted the record from the database successfully
There's a shorter way:
BSON::ObjectId("id_here")
but for your case it would be easier to simply map the objects to ids before the comparison:
if my_array_of_BSON_ObjectIds..map(&:to_s).include?(#my_id_as_a_string)

Resources