how to query the key exists in mongoid or mongo(ruby) - ruby

{"_id":{"$oid":"5ee9e17e88adc3a1d6c2a39f"},"title":"test","products":{"car":"yes hello"}}
how can I query the documents which have the key car use mongo _id or mongo?
I tried
irb(main):042:0> x = client[:materials].find({"products.car":{$exists=>true}})
=> #<Mongo::Collection::View:0x47269370736460 namespace='db.materials' #filter={"products.car"=>{nil=>true}} #options={}>
irb(main):043:0> x.count
Traceback (most recent call last):
1: from (irb):43
BSON::InvalidKey (NilClass instances are not allowed as keys in a BSON document.)
and I don't know how to do it with mongo _id or mongo. and puzzled about the error message

You do need to quote the $exists, but you also are not using the right search method. The method .find expects a document id, but you are passing it a query string.
If you only want the first record that matches your query, use:
.find_by("products.car":{"$exists"=>true})
If you want all records that match your query, use:
.where("products.car":{"$exists"=>true})

{$exists=>true}
This references the global variable $exists. Try:
{"$exists"=>true}

Related

How to Query Spring Data Neo4j with List Argument

I am trying to execute the query "find all merchants whose ids are in this list" (where the id is #GeneratedValue UUID string) in my spring data neo4j application.
Using query methods, that would (AFAIK) translate to either of:
List<Merchant> findByIdIn(List<String> ids);
List<Merchant> findByIdIsIn(List<String> ids);
In my swagger UI, I can see the endpoints, but when I pass in a valid id, no results are returned:
However, if I execute the same method programatically, the correct results are returned:
Similarly, the GET /merchants/90c55d4b-b3dc-4ae3-ab43-4d6ff523a20b endpoint returns the expected element.
This leads me to believe the internal translation of the HTTP request to the query isn't correct (most likely due to the list arg). The exact same thing happens (no results are returned) if I use a custom #Query, despite using the accepted solution from this s/o question:
#Query("MATCH (m: Merchant)" +
"WHERE m.id in $merchantId " +
"RETURN m")
List<Merchant> customQuery(List<String> merchantIds);
Am I missing something here? How do I query using a list as an argument? Thanks!

How to match exact Id within Comma seperated database column using LINQ and Lambda

Hi I have SQL Table where I am storing values like this:
Column Name: Registration_ID
180,1801,1803,18011,220
180,1801,
180,1801,1803
No I want to match exact Registration_ID and get records based on the Registration_ID. I have tried Contains but is not matching exact values.
Here is my query:
var Result=db.Entity_StudentRepository.Get(x =>
x.Registration_ID.Contains(Used_For_Id.ToString())).Select(x => x.Registration_ID).ToArray();
Could you please try the following query and let know if it works-
db.Entity_StudentRepository.AsEnumerable().Where(t=> Registration_ID.Split(',').Select(int.Parse).Contains(Used_For_Id));

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 index for filter + orderby

Lets say a comments table has the following structure:
id | author | timestamp | body
I want to use index for efficiently execute the following query:
r.table('comments').getAll("me", {index: "author"}).orderBy('timestamp').run(conn, callback)
Is there other efficient method I can use?
It looks that currently index is not supported for a filtered result of a table. When creating an index for timestamp and adding it as a hint in orderBy('timestamp', {index: timestamp}) I'm getting the following error:
RqlRuntimeError: Indexed order_by can only be performed on a TABLE. in:
This can be accomplished with a compound index on the "author" and "timestamp" fields. You can create such an index like so:
r.table("comments").index_create("author_timestamp", lambda x: [x["author"], x["timestamp"]])
Then you can use it to perform the query like so:
r.table("comments")
.between(["me", r.minval], ["me", r.maxval]
.order_by(index="author_timestamp)
The between works like the get_all did in your original query because it gets only documents that have the author "me" and any timestamp. Then we do an order_by on the same index which orders by the timestamp(since all of the keys have the same author.) the key here is that you can only use one index per table access so we need to cram all this information in to the same index.
It's currently not possible chain a getAll with a orderBy using indexes twice.
Ordering with an index can be done only on a table right now.
NB: The command to orderBy with an index is orderBy({index: 'timestamp'}) (no need to repeat the key)
The answer by Joe Doliner was selected but it seems wrong to me.
First, in the between command, no indexer was specified. Therefore between will use primary index.
Second, the between return a selection
table.between(lowerKey, upperKey[, {index: 'id', leftBound: 'closed', rightBound: 'open'}]) → selection
and orderBy cannot run on selection with an index, only table can use index.
table.orderBy([key1...], {index: index_name}) → selection<stream>
selection.orderBy(key1, [key2...]) → selection<array>
sequence.orderBy(key1, [key2...]) → array
You want to create what's called a "compound index." After that, you can query it efficiently.
//create compound index
r.table('comments')
.indexCreate(
'author__timestamp', [r.row("author"), r.row("timestamp")]
)
//the query
r.table('comments')
.between(
['me', r.minval],
['me', r.maxval],
{index: 'author__timestamp'}
)
.orderBy({index: r.desc('author__timestamp')}) //or "r.asc"
.skip(0) //pagi
.limit(10) //nation!
I like using two underscores for compound indexes. It's just stylistic. Doesn't matter how you choose to name your compound index.
Reference: How to use getall with orderby in RethinkDB

Mongoid where clause ruby hash

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

Resources