mongodb入门-9 查询4

不是很喜欢写博客,但是为了让自己学到东西,再不喜欢也逼着自己写博客.现在写博客之余跟同宿舍的同学打一场LOL还算是比较有意思的.马上就要毕业了,想想大学四年啊,错过了那么多啊.像空间里写的青春终将逝去.

继续写查询吧,希望在这篇文章能将查询的基本写完.

$elemMatch

匹配内嵌文章中的数据,我们知道在mongodb中可以使用内嵌文档,但是这时候根据内嵌文档的内容查询使用原先介绍的方法,可能就不是那么方便了,好在mongodb已经考虑了,为我们提供了$elemMatch方法.例子:

> db.user.find()
{ "_id" : ObjectId("5198c286c686eb50e2c843b2"), "name" : "user0", "age" : 0 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b3"), "name" : "user1", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b4"), "name" : "user2", "age" : 2 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b5"), "name" : "user3", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b6"), "name" : "user4", "age" : 1 }
{ "_id" : ObjectId("5198c286c686eb50e2c843b7"), "name" : "user5", "age" : 2 }
{ "_id" : ObjectId("51997c702b76790566165e48"), "name" : "xiangyue", "age" : 23, "title" : [ { "content" : "aaa" }, {
 "content" : "bbb" }, { "discuss" : "cc" } ] }
{ "_id" : ObjectId("51997c9f2b76790566165e49"), "name" : "xiangyue", "age" : 23, "title" : [ { "content" : "dd" }, {
"content" : "ee" }, { "discuss" : "ff" } ] }
> db.user.find({title:{$elemMatch : {content : "aaa"}}}) -->查找title中的content字段为aaa的文档
{ "_id" : ObjectId("51997c702b76790566165e48"), "name" : "xiangyue", "age" : 23, "title" : [ { "content" : "aaa" }, {
 "content" : "bbb" }, { "discuss" : "cc" } ] }

游标

mongodb中提供了像关系型数据库中的游标操作.首先我们获取一个游标,获取游标很简单,只需要将我们以前学过的查询方法赋值给一个变量就可以了:

var cursor = db.test.find()
我们如果在命令行直接输入cursor,将会执行这个查询打印结果,这个时候我们再去执行cursor的时候将神马都不会返回了,因为这个游标已经使用完了,当然我们不想这样使用游标,我们可以像下面那样使用游标:

> while(cursor.hasNext()){ var current = cursor.next(); print("age=" + current.age); }
age=1
age=2
age=3
age=4
age=5
当然我们可以使用游标的forEach方法,如下:

> var cursor = db.test.find()
> cursor.forEach(function(obj){
... print("age=" + obj.age);
... });
age=1
age=2
age=3
age=4
age=5
同样游标可以结合sort/skip/limit等方法一同使用,换句话说以前学的基本所有的查询都可以跟游标结合使用.

count 计算查询结果的数目

这个比较简单,在以前的查询的命令后面再加上.count()就可以了.

> db.test.find()
{ "_id" : 1, "name" : "user_1", "age" : 1 }
{ "_id" : 2, "name" : "user_2", "age" : 2 }
{ "_id" : 3, "name" : "user_3", "age" : 3 }
{ "_id" : 4, "name" : "user_4", "age" : 4 }
{ "_id" : 5, "name" : "user_5", "age" : 5 }
> db.test.find().count()
5

null查询

例如下面文档我们只想查出y值为null的文档,

> db.test2.find()
{ "_id" : ObjectId("519984432b76790566165e4c"), "x" : null }
{ "_id" : ObjectId("5199844c2b76790566165e4d"), "y" : null, "x" : "test" }

按照我们原来学过的使用下的方式查询结果不是我们想要的:

> db.test2.find({y:null}) -->我们发现mongodb对于y不存在也会给查出来
{ "_id" : ObjectId("519984432b76790566165e4c"), "x" : null }
{ "_id" : ObjectId("5199844c2b76790566165e4d"), "y" : null, "x" : "test" }
这里提供一下两种方法查询

> db.test2.find({y:{$type:10}}) -->明确指出其类型
{ "_id" : ObjectId("5199844c2b76790566165e4d"), "y" : null, "x" : "test" }
> db.test2.find({y:null,y:{$exists:1}}) -->查找null 但是同时y值必须存在
{ "_id" : ObjectId("5199844c2b76790566165e4d"), "y" : null, "x" : "test" }


到这里mongodb的查询基本我算是介绍完了,欢迎读者补充.


你可能感兴趣的:(mongodb入门-9 查询4)