Reputation: 121
{"_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
Upvotes: 0
Views: 1556
Reputation: 77
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})
Upvotes: 1
Reputation: 14520
{$exists=>true}
This references the global variable $exists
. Try:
{"$exists"=>true}
Upvotes: 0