Example of work with mongo

Hi there,
I'm newbie here and I have a problem with the connection with MongoDB.
The connection among Rails and MongoDB works, but I don't know, how to
print only one "column" from document.
If I'm trying following a part of code:

puts db["testCollection"].find_one().inspect

So I'will get the entire structure of BSON, as:

{"_id"=>#<BSON::ObjectID:0x118576c ...>, "name"=>"MongoDB",
"info"=>{"x"=>203, "y"=>102}, "type"=>"database", "count"=>1}

But I would like to ask you, how is possible to get only the item eg
"name"... I am searching this information a long time, but no result
yet...

I will very glad for everything help, thanks a lot!

db["testCollection"].find_one['name']

Hint: `db["testCollection"].find_one.methods.sort` will give you a lot
of useful information...

Hi Hassan,
thanks for your reply.

This works, but if I am trying to select only one attribut from the
whole document,

db["testCollection"].find['name']

so that isn't working. I must to type:

@array=db.collection('people').find() #I'm selecting everything :confused:
i=0
for polozka in @array
  puts "#{i}th item is: #{polozka['name']}"
  i+=1
end

Can you help with this? Thanks in advance!

I think you will find that this will work better. It will return an array of just the people’s names and then you can iterate over them.

arr_person = Person.find(:all).map {|p| p.name}

arr_person.each_with_index{|p,i| puts “#{i} has the name: #{p}”}

B.

I'm not sure if you're trying to get only documents with a given name
or show the names of all documents, but have you gone through this:

<http://api.mongodb.org/ruby/current/file.TUTORIAL.html>

It will probably give you a good overall picture.

HTH!

It would if the OP were using ActiveRecord with a Person object, but
the question is about MongoDB :slight_smile:

db.collection('people').find().each_with_index { |x,y| puts "#{y}
#{x['name']}" }

would actually work...

Simple blog built with MongoDB http://rad-sample.heroku.com
sources https://github.com/alexeypetrushin/rad_sample

More examples:

Save any pure Ruby object (also complex & nested) in MongoDB
https://github.com/alexeypetrushin/mongo_db

+ driver API enhancements (100% backward-compatible with original API),
makes API more friendly & handy, no extra abstraction or complexities
introduced, all things are exactly the same as in MongoDB.