时间:2021-07-01 10:21:17 帮助过:4人阅读
{ "name" : "peter", "position" : "teacher" }> db.shiyanlou.insert(doc)> doc1=({"name": "tom", "position": "student"}){ "name" : "tom", "position" : "student" }> db.shiyanlou.insert(doc1)-1,条件操作符:
> db.shiyanlou.find(){ "_id" : ObjectId("5559d1cca30df8c25bf44dd7"), "name" : "peter", "position" :"teacher" }{ "_id" : ObjectId("5559d1e9a30df8c25bf44dd8"), "name" : "tom", "position" : "student" }>
-3,limit : 读取指定数量的记录
db.shiyanlou.find({"name": {$type:2}}){ "_id" : ObjectId("5559d1cca30df8c25bf44dd7"), "name" : "peter", "position" :"teacher" }{ "_id" : ObjectId("5559d1e9a30df8c25bf44dd8"), "name" : "tom", "position" : "student" }
-4,skip:读取时跳过指定数据记录
> db.shiyanlou.find().limit(1){ "_id" : ObjectId("5559d1cca30df8c25bf44dd7"), "name" : "peter", "position" :"teacher" }>
-5,sort 排序 1 表示升序,-1表示降序
> db.shiyanlou.find().limit(1).skip(2)> db.shiyanlou.find().limit(1).skip(1){ "_id" : ObjectId("5559d1e9a30df8c25bf44dd8"), "name" : "tom", "position" : "student" }
3,索引: db.collection_name.ensureIndex()
db.shiyanlou.find().sort({"name": 1}){ "_id" : ObjectId("5559d1cca30df8c25bf44dd7"), "name" : "peter", "position" :"teacher" }{ "_id" : ObjectId("5559d1e9a30df8c25bf44dd8"), "name" : "tom", "position" : "student" }> db.shiyanlou.find().sort({"name":-1}){ "_id" : ObjectId("5559d1e9a30df8c25bf44dd8"), "name" : "tom", "position" : "student" }
ensureIndex()的可选参数:
| 参数 | 类型 | 描述 |
|---|---|---|
| background | Boolean | 建立索引要不要阻塞其他数据库操作,默认为false |
| unique | Boolean | 建立的索引是否唯一,默认false |
| name | string | 索引的名称,若未指定,系统自动生成 |
| dropDups | Boolean | 建立唯一索引时,是否删除重复记录,默认flase |
| sparse | Boolean | 对文档不存在的字段数据不启用索引,默认false |
| expireAfterSeconds | integer | 设置集合的生存时间,单位为秒 |
| v | index version | 索引的版本号 |
| weights | document | 索引权重值,范围为1到99999 |
| default-language | string | 默认为英语 |
| language_override | string | 默认值为 language |
MongoDB基础--查询、索引与聚合
标签: