user3788685
user3788685

Reputation: 3113

find() from MongoDB, return result, supress fields and turn into JSON

I Have data saved in a MongoDB in the following format

{"_id": "VALVE22","state": "1","element": "BNK1FLOW","data":{"type": "SEN","descr": "TOWER6"}}

I have the following code in a Ruby script;

db = Mongo::Connection.new.db("cooler-lookup")
coll = db.collection("elements")
kitty = coll.find({"_id" => table[address][i], "state" => char}).to_a

'table[address][i]' and 'char' are variables defined & used elsewhere in the bigger script feeding data into this lookup section. For testing these can be replaced with "VALVE22" and "1" respectively (and that's how I've been testing in irb)

When run from the command line the script outputs the following correct result from a valid query.

{"_id"=>"VLAVE22", "state"=>"1", "element"=>"BNK1FLOW", "data"=>{"type"=>"SEN", "descr"=>"TOWER6"}}

But I need to suppress the _id and state fields. I've tried using :fields modifier in all sorts of ways but can't remove the fields. I have tested this in irb and along with the valid lookup I also get => nil returned. I'm sure this is something really simple but I can't see what I need to be able to JSON.generate the query results without the ID & State fields and then puts it.

Using the code below I was able to get this working, however when I tried to do kittylitter = JSON.generate(kitty) I was getting a lot of empty []'s as well as my valid result. It looks like they where the failed queries from the DB coming back with no record.

After many hours of being confused I managed to find this bit of code to fix the problem

kitty.each do |key|
keyjson = JSON.generate(key)
puts keyjson
end

That gave me exactly what I needed out - which was the result on 1 line as valid JSON. Part of my head hurting confusion comes from the fact to.a makes an array, yet when I tried to do array type stuff on the result kitty nothing would work as expected. I then tried treating it like a hash which led me to that bit of code above! Once I'd done that everything worked... Am I wrong to be confused by arrays and hashes or have I missed something real obvious like my array is or contains a hash?

Upvotes: 1

Views: 983

Answers (2)

rrrrrraul
rrrrrraul

Reputation: 121

Using gem mongo -v 2.4.3 , the following works for me

mongo_results = collection.find({"shop_id" => shop_id}, :projection => {"_id" => 0, "child_products" => 0}).to_a

In the example above, I'm omitting "_id" and "child_products" from showing up in the results.

Upvotes: 0

Mark Silverberg
Mark Silverberg

Reputation: 1259

This works for me:

kitty = coll.find({"_id" => table[address][i], "state" => char}, :fields => {"_id" => 0, "state" => 0}).to_a

It returns

[{"element"=>"BNK1FLOW", "data"=>{"type"=>"SEN", "descr"=>"TOWER6"}}] 

See http://api.mongodb.org/ruby/current/Mongo/Collection.html#find-instance_method for usage instructions for Mongo::Collection#find

Upvotes: 1

Related Questions