11155
(-- --)
March 4, 2011, 12:41am
1
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!
hassan
(Hassan Schroeder)
March 4, 2011, 12:56am
2
db["testCollection"].find_one['name']
Hint: `db["testCollection"].find_one.methods.sort` will give you a lot
of useful information...
11155
(-- --)
March 4, 2011, 4:30pm
3
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
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.
hassan
(Hassan Schroeder)
March 4, 2011, 4:59pm
5
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!
hassan
(Hassan Schroeder)
March 4, 2011, 5:17pm
6
It would if the OP were using ActiveRecord with a Person object, but
the question is about MongoDB
db.collection('people').find().each_with_index { |x,y| puts "#{y}
#{x['name']}" }
would actually work...
11155
(-- --)
August 13, 2011, 5:49am
7
11155
(-- --)
August 18, 2011, 10:10pm
8
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.