mongodb 查询文档的语法如下:
db.collection_name.find(query, projection) # 以压缩格式返回数据
db.collection_name.find(query, projection).pretty() # 以易读格式返回数据
# 查询 testdb.artciles 集合中的所有文档
> use testdb
> db.articles.find().pretty()
# 查询 testdb.articles 集合中 author='assad' 的文档
> db.atricles.find( { author:'assad' } )
> use testdb
# 查询 testdb.articles 集合中 author="assad" 的文档
> db.articles.find( { author:'assad' } )
# 查询 likes > 1000 的文档
> db.articles.find( { likes:{$gt:1000} } )
# 查询 likes 大于 1000 ,小于 1500 的文档
> db.artciles.find( { likes:{$gt:1000, $lt:1500} } )
# 查询 author="assad" 同时 likes > 2000 的文档
> db.articles.find( { author:'assad', likes:{$gt:2000} } )
# 查询 authoer="assad" 或 "vancy" 的文档
> db.articles.find( { author:{$in:['assad','vancy']} } )
# 查询 tages 数组同时含有 'java','groovy' 的文档
> db.articles.find( { tages:{ $all:['java','groovy']} } )
# 查询 title 中含有 'java' 字段
使用 find() 函数的 projection 参数限定返回键
# 查询 testdb.article 集合中所有的文档,只返回 title,author,这2个键(默认会返回 _id 键)
> db.articles.find( {}, {title:1, author:1} )
{ "_id" : ObjectId("5a83c281a04c12209d79eea3"),"title" : "groovy refrence","author" : "assad" }
{ "_id" : ObjectId("5a83c5a0a04c12209d79eea4"),"title" : "spring refrence","author" : "alex" }
# 同上,不返回 _id 键
> db.articles.find( {}, {title:1, author:1, _id:0} )
{ "title" : "groovy refrence", "author" : "assad" }
{ "title" : "spring refrence", "author" : "alex" }