设为首页 收藏本站
查看: 3522|回复: 0

[经验分享] MongoDB—— 读操作 Core MongoDB Operations (CRUD)

[复制链接]

尚未签到

发表于 2015-7-7 12:10:12 | 显示全部楼层 |阅读模式
  本文主要介绍内容:从MongoDB中请求数据的不同的方法

Note:All of the examples in this document use the mongo shell interface. All of these operations are available in an idiomatic interface for each language by way of the MongoDB Driver. See your driver documentation for full API documentation.

Queries in MongoDB 查询
find()
主要有find()和findOne()两种查询的方法,find()具体语法如下:
  db.collection.find( ,  )
All queries in MongoDB address a single collection. 所有查询操作都在一个集合中进行。
ps:可以在数据库打开后,键入db指令,查看当前的数据库;键入show collections 查看所有的集合。
其中限制查询筛选条件,如果为空,则返回所有的文档(documents)。
限制返回的查询结果的域。
findOne()
findOne()不同之处:返回值类型为一个文档而不是游标(类似指针)。
具体语法如下:
db.collection.findOne( ,  )

Query Document
下面看一些的例子:
   db.inventory.find( { type: 'food', price: { $lt: 9.95 } }, { item: 1, qty: 1 } )
在inventory集合中,查找type为food,price少于9.95的文档,返回这些文档的item和qty以及_id。该函数返回值类型为游标。
db.inventory.find({}) 查询集合中的所有文档,也能写成edb.inventory.find()。
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )筛选集合中type值为food或snacks的文档。
db.inventory.find( { $or: [ { qty: { $gt: 100 } },
                            { price: { $lt: 9.95 } } ]
                   } )筛选qty大于100或者price小于9.95的记录。
同一个域中的“或” 使用$in表示,不同域之间的“或”使用$or表示。
筛选子文档:
db.inventory.find( {
                     producer: {
                                 company: 'ABC123',
                                 address: '123 Street'
                               }
                   }
                 )
上面的例子可以使用点符号简化,如下:
db.inventory.find( { 'producer.company': 'ABC123' } )
筛选第一个子文档by域为shipping的所有的文档
db.inventory.find( { 'memos.0.by': 'shipping' } )
筛选至少有一个子文档by域为shipping的所有的文档
db.inventory.find( { 'memos.by': 'shipping' } )

Result Projections
下面看一些的例子:
结果包含item和qty域以及默认的_id域:
db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )
排除结果中默认的_id域:
db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )


高级查询的补充知识:
摘自http://www.iyunv.com/zhy4606/archive/2011/09/13/2175220.html
$all 匹配所有
这个操作符跟SQL语法的in类似,但不同的是, in只需满足( )内的某一个值即可,  而$all必须满足[ ]内的所有值,例如:
db.users.find({age : {$all : [6, 8]}});  
可以查询出  {name: 'David', age: 26, age: [ 6, 8, 9 ] }  
但查询不出  {name: 'David', age: 26, age: [ 6, 7, 9 ] }
$exists 判断字段是否存在
查询所有存在age字段的记录  
db.users.find({age: {$exists: true}});  
查询所有不存在name字段的记录  
db.users.find({name: {$exists: false}});

Null 值处理
> db.c2.find({age:null})   
$mod 取模运算
查询age取模6等于1的数据
db.c1.find({age: {$mod : [ 6 , 1 ] } })

$ne 不等于
查询x的值不等于3 的数据
db.c1.find( { age : { $ne : 7 } } );

$in 包含
db.c1.find({age:{$in: [7,8]}});

$nin 不包含
查询age的值在7,8 范围外的数据  
db.c1.find({age:{$nin: [7,8]}});

$size 数组元素个数
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
匹配db.users.find({favorite_number: {$size: 3}});
不匹配db.users.find({favorite_number: {$size: 2}});


正则表达式匹配
查询name 不以T开头的数据
db.c1.find({name: {$not: /^T.*/}});  

Javascript 查询和$Where查询
查询a大于3的数据,下面的查询方法殊途同归
db.c1.find( { a : { $gt: 3 } } );
db.c1.find( { $where: "this.a > 3" } );
db.c1.find("this.a > 3");
f = function() { return this.a > 3; } db.c1.find(f);  

count 查询记录条数
db.users.find().count();
以下返回的不是5,而是user 表中所有的记录数量
db.users.find().skip(10).limit(5).count();
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
db.users.find().skip(10).limit(5).count(true);  

skip限制返回记录的起点
从第3 条记录开始,返回5 条记录(limit 3, 5)
db.users.find().skip(3).limit(5);

Indexes索引
使用db.collection.ensureIndex()方法创建索引。
db.collection.ensureIndex( { : , : , ... } )
其中order选项,1表示升序,-1表示降序
The explain() cursor method allows you to inspect the operation of the query system, and is useful for analyzing the efficiency of queries, and for determining how the query uses the index.
db.inventory.find( { type: 'food' } ).explain()
可以通过查看描述,分析建立索引前后查询效率的变化。MongoDB使用B树建立索引。
Cursors游标
范例:
var myCursor = db.inventory.find( { type: 'food' } );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;
if (myDocument) {
    var myItem = myDocument.item;
    printjson(myItem);
}
或者使用javascript语法:
var myCursor =  db.inventory.find( { type: 'food' } );
myCursor.forEach(printjson);
游标在10分钟后会自动回收,如果想要去除时间限制,设置如下:
var myCursor = db.inventory.find().addOption(DBQuery.Option.noTimeout);
Cursor Flags
mongo shell提供了以下cursor flags:
    DBQuery.Option.tailable
    DBQuery.Option.slaveOk
    DBQuery.Option.oplogReplay
    DBQuery.Option.noTimeout
    DBQuery.Option.awaitData
    DBQuery.Option.exhaust
    DBQuery.Option.partial

集合操作(aggregation)
包括以下四种:
    count (count())
    distinct (db.collection.distinct())
    group (db.collection.group())
    mapReduce. (Also consider mapReduce() and Map-Reduce.)
从Sharded Clusters中读取数据
从Replica Sets中读取数据

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-84106-1-1.html 上篇帖子: mongoDB index introduction 下篇帖子: Redhat 5.5下安装MongoDB
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表