MongoMapper 运行简单的 MongoDB 查询
我正在运行 Rails 应用程序并使用 MongoDB 作为数据库存储。对于数据映射部分,我使用 MongoMapper gem。
如果我想模仿 ActiveRecord 模型的功能,MongoMapper 很棒,但我的问题是是否可以通过 MongoMapper 运行简单的 MongoDB 查询,例如直接查询集合(即没有显式模型,包括字段等) on)或者我应该使用 mongo gem 作为 ruby?
谢谢
I am running a Rails application and using MongoDB as database store. For the data mapping part I use the MongoMapper gem.
MongoMapper is great if I want to mimic the functionality of ActiveRecord models, but my question is if it is possible or not to run simple MongoDB queries thorugh MongoMapper, like directly querying a collection(namely without an explicit Model, who includes the fields and so on) or I should use the mongo gem for ruby?
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我主要是从 如何在 Ruby 中直接触发原始 MongoDB 查询中偷来的
否则我猜你会使用 from_uri 构造函数来构建你自己的连接。
然后您需要获得一个数据库,您可以使用数组访问符号、db 方法来完成此操作,或者直接从 MongoMapper 获取当前数据库:
现在您手中拥有了一个漂亮闪亮的 Mongo::DB 实例。但是,您可能希望 Collection 做任何有趣的事情,您可以使用数组访问表示法或集合方法来实现:
现在您有了一些行为类似于 SQL 表的东西,因此您可以计算它有多少东西或查询它使用 find:
等
输出一行
现在你有了你真正想要的东西:一个热出炉的 Mongo::Cursor 指向你感兴趣的数据。 Mongo::Cursor 是一个 Enumerable 所以你有访问您常用的所有内容迭代朋友,例如 every、first、map 和我个人最喜欢的each_with_object:
I stole this mostly from How to fire raw MongoDB queries directly in Ruby
Otherwise I guess you'd use the from_uri constructor to build your own connection.
Then you need to get your hands on a database, you can do this using the array access notation, the db method, or get the current one straight from MongoMapper:
Now you have a nice shiny Mongo::DB instance in your hands. But, you probably want a Collection to do anything interesting and you can get that using either array access notation or the collection method:
Now you have something that behaves sort of like an SQL table so you can count how many things it has or query it using find:
etc.
output a row
And now you have what you're really after: a hot out of the oven Mongo::Cursor that points at the data you're interested in. Mongo::Cursor is an Enumerable so you have access to all your usual iterating friends such as each, first, map, and one of my personal favorites, each_with_object: