二、查询语句
1、find() 语句
启动MongoDB服务,因为mongoDB并不随系统一起启动,可能以下命令运行后会等一小段的时间才会启动完毕。
$ sudo service mongodb start
进入MongoDB命令行操作界面,在命令行中敲exit可以退出
$ mongo
find() 用法:db.COLLECTION_NAME.find()
> use post
> db.post.insert([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'shiyanlou',
url: 'http://www.shiyanlou.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
title: 'NoSQL Database',
description: "NoSQL database doesn't have tables",
by: 'shiyanlou',
url: 'http://www.shiyanlou.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 20,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
查询数据,不加任何参数默认返回所有数据记录:
> db.post.find()
2、pretty() 语句
pretty() 可以使查询输出的结果更美观。
> db.post.find().pretty()
三、MongoDB中的 AND
1、AND
当 find() 中传入多个键值对时,MongoDB就会将其作为 AND 查询处理。用法:db.mycol.find({ key1: value1, key2: value2 }).pretty()
> db.post.find({"by":"shiyanlou","title": "MongoDB Overview"}).pretty()
四、MongoDB中的 OR
1、OR
MongoDB中,OR 查询语句以 $or 作为关键词,用法如下:
> db.post.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
操作示例:
> db.post.find({
$or:[
{"by":"shiyanlou"},
{"title": "MongoDB Overview"}
]
}).pretty()
五、同时使用 AND 和 OR
1、操作范例
> db.post.find({
"likes": {$gt:10},
$or: [
{"by": "shiyanlou"},
{"title": "MongoDB Overview"}
]
}).pretty()
{\$gt:10} 表示大于10,另外,\$lt 表示小于,\$lte 表示小于等于,\$gte 表示大于等于,\$ne 表示不等于。
六、小结
本节讲了MongoDB中的查询,find可以查询集合的所有数据,find中添加AND和OR条件查询,{\$gt:10} 表示大于10,另外,\$lt 表示小于,\$lte 表示小于等于,\$gte 表示大于等于,\$ne 表示不等于。