上篇 blog 学习了 MongoDB 的插入,接下来学习数据查询相关的内容。MongoDB 查询有好几种方法,具体为以下:
基础表
1 |
> db.test_2.find(); |
1 使用 Find 游标查询
1 |
var cursor=db.test_2.find(); |
备注:通过 while 循环,使用 next() 方法依次读取所有 document,并用 printjson 方法显示结果。
2 使用 Find 的 forEach()查询
1 |
> db.test_2.find().forEach(printjson); |
3 定制查询
MongoDB 的查询和关系型数据库的查询差异较大,但大多数据的关系型数据库的查询可以转换成MongoDB 的查询,以下为简单的几种情况。
3.1 select * From test_2;
1 |
> db.test_2.find(); |
3.2 select id,name from test_2;
1 |
> db.test_2.find({},{id:1,name:1}); |
3.3 select id from test_2;
1 |
> db.test_2.find({},{id:1}); |
3.4 select * From test_2 where id=1;
1 |
> db.test_2.find({id:1}); |
3.5 select id,address from test_2 where id=4;
1 |
> db.test_2.find({address:'zhoushan'},{id:1,name:1}); |
3.6 select * from test_2 where id=1 and name=’francs’
1 |
> db.test_2.find({id:1,name:'francs'}); |
备注:先学习这么多,其它更复杂的查询以后再补充。
4 Limit 用法
1 |
> db.things.find();db.things.find(); |
5 Skip 用法
1 |
> db.things.find()10).limit(1); ( |
6 Sorting 用法
1 |
db.things.find().sort({id:1}); |
7 附:db.collection.find
The find() method selects documents in a collection and returns a cursor to the selected documents.
The find() method takes the following parameters.
Parameters:
1 query (document) – Optional. Specifies the selection criteria using query operators. Omit
the query parameter or pass an empty document (e.g. {}) to return all documents in the collection.
2 projection (document) –
Optional. Controls the fields to return, or the projection. The projection argument will resemble the
following prototype:
{ field1: boolean, field2: boolean … }
The boolean can take the following include or exclude values:
1 or true to include. The find() method always includes the _id field even if the field is not explicitly
stated to return in the projection parameter.
0 or false to exclude.
The projection cannot contain both include and exclude specifications except for the exclusion of the _id field.
Returns:
A cursor to the documents that match the query criteria and contain the projection fields.
原创文章,作者:6024010,如若转载,请注明出处:https://blog.ytso.com/237908.html