MongoDB的简单使用-查询操作

MongoDB通过find()函数执行查询操作

1.查找集合内的全部文档:

db.media.find()

系统返回:

{ "_id" : ObjectId("5aa47c1953350e04ddbd6fa3"), "Type" : "Book", "Title" : "Definitive Guide to MongoDB 3rd ed.", "ISBN" : "978-1-4842-1183-0", "Publisher" : "Apress", "Author" : [ "Hows,David", "Plugge,Eelco", "Membrey,Peter", "Hawkins,Tim" ] }
{ "_id" : ObjectId("5aa47dd553350e04ddbd6fa4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Titie" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }

显示出上篇文章我们添加的2个文档

2.查找Nirvana的所有CD:

db.media.find({Artist:"Nirvana"})

系统返回:

{ "_id" : ObjectId("5aa47dd553350e04ddbd6fa4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Titie" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }

3.查找Nirvana的所有CD的标题:

db.media.find({Artist:"Nirvana"},{Title:1})

系统返回:

{ "_id" : ObjectId("5aa47dd553350e04ddbd6fa4"), "Title" : "Nevermind" }

查找Nirvana的所有CD的非标题信息

db.media.find({Artist:"Nirvana"},{Title:0})

系统返回:

{ "_id" : ObjectId("5aa47dd553350e04ddbd6fa4"), "Type" : "CD", "Artist" : "Nirvana", "Tracklist" : [ { "Track" : "1", "Titie" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }

4.查找内嵌对象文档的信息:

db.media.find({"Tracklist.Title":"In Bloom"})

系统将返回对应文档的全部信息

{ "_id" : ObjectId("5aa47dd553350e04ddbd6fa4"), "Type" : "CD", "Artist" : "Nirvana", "Title" : "Nevermind", "Tracklist" : [ { "Track" : "1", "Titie" : "Smells Like Teen Spirit", "Length" : "5:02" }, { "Track" : "2", "Title" : "In Bloom", "Length" : "4:15" } ] }

5其他相关函数

  sort()排序函数 db.media.find().sort({Title:1})      #1为升序,-1为降序

  limit()限制返回结果的最大数目 db.media.find().limit(10)      #0表示返回所有结果

  skip()忽略集合中的前几个文档 db.media.find().skip(20)      

posted @ 2018-03-11 09:41  渡~solong  Views(173)  Comments(0Edit  收藏  举报