首页 技术 正文
技术 2022年11月17日
0 收藏 841 点赞 2,846 浏览 4069 个字

本文主要介绍内容:从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( <query>, <projection> )

All queries in MongoDB address a single collection. 所有查询操作都在一个集合中进行。
ps:可以在数据库打开后,键入db指令,查看当前的数据库;键入show collections 查看所有的集合。

其中<query>限制查询筛选条件,如果为空,则返回所有的文档(documents)。
<projection>限制返回的查询结果的域。

findOne()
findOne()不同之处:返回值类型为一个文档而不是游标(类似指针)。

具体语法如下:
db.collection.findOne( <query>, <projection> )

Query Document
下面看一些<query>的例子:

   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
下面看一些<projection>的例子:

结果包含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.cnblogs.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( { <field1>: <order>, <field2>: <order>, … } )

其中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中读取数据

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848