> db.test.getIndexes();
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "mydemo.test"
}
]
> db.inventory.ensureIndex({type:1,item:1})
> db.inventory.find({type:"food",item:"eee"}).explain()
- 过期索引: 一段时间后会过期的索引,在索引过期后,相应的数据会被删除
db.test3.insert({time:new Date()})
db.test3.insert({time:new Date()})
db.test3.ensureIndex({time:1},{expireAfterSeconds:30})
db.test3.insert({time:new Date()})
db.test3.insert({time:new Date()})
db.test3.find()
{ "_id" : ObjectId("5ddf7c57892bb00478875228"), "time" : ISODate("2019-11-28T07:50:47.629Z") }
{ "_id" : ObjectId("5ddf7c59892bb00478875229"), "time" : ISODate("2019-11-28T07:50:49.286Z") }
{ "_id" : ObjectId("5ddf7c7a892bb0047887522a"), "time" : ISODate("2019-11-28T07:51:22.608Z") }
{ "_id" : ObjectId("5ddf7c7b892bb0047887522b"), "time" : ISODate("2019-11-28T07:51:23.562Z") }
> db.test3.find()
> db.test5.insert({_id:1,info:'1 2 3'})
WriteResult({ "nInserted" : 1 })
> db.test5.insert({_id:2,info:"3 4 5"})
WriteResult({ "nInserted" : 1 })
> db.test5.ensureIndex({'info':'text'})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.test5.find({$text:{$search:"1"}})
{ "_id" : 1, "info" : "1 2 3" }
> db.test5.find({$text:{$search:"3"}})
{ "_id" : 1, "info" : "1 2 3" }
{ "_id" : 2, "info" : "3 4 5"
2D平面索引
2DSphere球面索引
db.test6.insert({w : [10, 10]});
db.test6.insert({w : [11, 10]});
db.test6.insert({w : [10, 11]});
db.test6.insert({w : [12, 15]});
db.test6.insert({w : [16, 17]});
db.test6.insert({w : [90, 90]});
db.test6.insert({w : [150, 160]});
db.test6.createIndex({"w" : "2d"})
$near" 查询:查询距离某个点最近的坐标点
"$geoWithin" 查询:查询某个形状内的点
db.test6.find({w : {"$near" : [11, 11]}})
#查询范围最大是5数据
db.test6.find({w : {"$near" : [11, 11], "$maxDistance" : 5}})
#查询矩形
db.test6.find({w:{"$geoWithin" : {"$box" : [[9, 9], [11, 11]]}}})
#查询圆形
db.test6.find({w:{"$geoWithin": {"$center" : [[10, 10], 2]}}})