mongoid--查询的注意事项
2016-04-29 19:35
603 查看
mongoid查询方法简介
mongoid是ruby版本的mongoldb-driver.mongoid实现的查询方法和active record极其类似,所以对于rails用户来说是很友好的。
例如:
class Band include Mongoid::Document field :name field :founded end Band.where(name: "Depeche Mode") Band. where(:founded.gte => "1980-1-1"). in(name: [ "Tool", "Deftones" ]). union. in(name: [ "Melvins" ])
注意事项
正常的wehre和in等查询方式,返回的结果是类似ActiveRecord::Relation的Mongoid::Criteria对象,可以链式调用,无限连接。而且Mongoid::Criteria对象和ActiveRecord::Relation类似,是懒执行的,也就是说除非调用了数组的方法,才会触发真正的查询,否则不会真的去连接mongodb和进行查询。
排序 sort
排序时使用sort方法,但是sort方法返回的对象是 Mongoid::Contextual::Mongo,这个对象是不支持再连接条件的。所以,排序要放到查询的后面!
支持分页查询功能 page,per
分页功能和rails的插件kaminary以及will_paginate都很相似,用page和per分别表示第几页和每页多少条记录。Band.where(name: "Depeche Mode").per(10).page(2).sort({ name: 1 })
page可以单独使用,但是per不可以。如果要用per,必须先加上page!
page和per的实质是用mongoldb的skip和limit实现的, 分别类似mysql的offset和limit
参考资料
https://docs.mongodb.org/ecosystem/tutorial/mongoid-queries/相关文章推荐
- mongoid--2d索引简介(index)
- 设计模式-建造者模式(Go语言描述)
- Zygote,SystemServer启动分析
- Googlehacking 信息收集
- LET'S DJ:web.py无缝迁移到django
- 使用GO语言创建一个Web应用
- googleHacking基础
- Windows7下面手把手教你安装Django
- GO语言初识与编程环境配置
- 谷歌浏览器插件“开眼”访问google、facebook等
- 九、Go语言库之strconv包--GO语言笔记
- UVA 11383 - Golden Tiger Claw【二分图km原理】
- 八、Go语言包之strings--go语言学习笔记
- 七、GO语言库学习--net/url包--go语言笔记
- django1.8读书笔记模版高级进阶
- 【Leetcode】:96. Unique Binary Search Trees 问题 in Go语言
- BZOJ4377: [POI2015]Kurs szybkiego czytania
- Go语言如何深度拷贝对象
- Go - 以任意类型的slices作为输入参数
- googlehacking语法基础