find() 语句
启动MongoDB服务,因为mongoDB并不随系统一起启动,可能以下命令运行后会等一小段的时间才会启动完毕。sudo service mongodb start
进入MongoDB命令行操作界面,在命令行中敲exit可以退出
mongo
find() 用法:db.COLLECTION_NAME.find()
> use post #创建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()
pretty() 语句
pretty() 可以使查询输出的结果更美观。db.post.find().pretty()
MongoDB中的 AND
当 find() 中传入多个键值对时,MongoDB就会将其作为 AND 查询处理。用法:db.mycol.find({ key1: value1, key2: value2 }).pretty()
db.post.find({"by":"shiyanlou","title": "MongoDB Overview"}).pretty()
MongoDB中的 OR
MongoDB中,OR 查询语句以 $or 作为关键词,用法如下:> db.post.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
同时使用 AND 和 OR
> db.post.find({
"likes": {$gt:10},
$or: [
{"by": "shiyanlou"},
{"title": "MongoDB Overview"}
]
}).pretty() #{\$gt:10} 表示大于10,另外,\$lt 表示小于,\$lte 表示小于等于,\$gte 表示大于等于,\$ne 表示不等于。