0

I'm working with MongoDB using Ruby.

I am able to query a document by doing something like this:

client[:inventory].find({"owner": identity}, projection: {"_id": 0, "group": 1}).each do |doc| 
  #Finds and returns a BSON document matching the query.
  puts doc.to_s
end

However this gives the following key/value pair in String representation:

{"name" => "john"}

How would I retrieve only the value from the returned BSON document, removing the braces and hash rocket, in this case john?

1 Answer 1

1

Since doc is a simple hash, you can call .values method on it, returning values of the hash. And if you're sure there is only one pair of key-value, or you need only the first one, try this:

- puts doc.to_s
+ puts doc.values.first
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.