MongoDB基础操作及根据地图距离范围查询,附近商家查询,附件兴趣点查询
启动mongodb服务
./mongod --config ./mongodb.conf
添加用户
use admin
db.createUser({user:"admin",pwd:"Ruomima123",roles:[{role:"root",db:"admin"}]});
db.createUser({user:"root",pwd:"root123!@#",roles:["root"]})
db.auth('admin','Ruomima123')
use mylocation
db.createUser({user:"app",pwd:"app123!@#",roles:["readWrite"]})
#其他
db.system.users.find() # 查看当前帐户(密码有加密过)
db.system.users.remove({}) # 删除所有帐户
#开启认证
./mongod --auth --config ./mongodb.conf
或在conf里加
auth=true
#mongodb.conf
------------------
dbpath=/home/lvz/db
logpath=/home/lvz/app/mongodb/logs/mongodb.log
port=27017
fork=true
logappend=true
-------------------
#关闭mongodb
$ ./mongod
> use admin
> db.shutdownServer()
方法二
./mongod --shutdown -f ./mongodb.conf
#基本查询
db.getCollection('location').find({},{'time':1}).sort({'time':-1}).limit(5)
db.location.find({'time':{$gte:ISODate('2017-09-01')}}).limit(20)
**注意**
py里时间要用datetime方法生成时间对象后比较。
from datetime import datetime
start=datetime(2017,8,1,20,50,59,100);
db.location.find({'time':{'$gte':start}}).limit(20)
#分组查询
db.getCollection('location').group({
key:{trip:true},
initial:{num:0},
$reduce:function(doc,prev){
prev.num++
},
condition:{
$where:function(){
return this.trip >='201708140000000000000'
}
}
});
#分组二(spring-data-mongo 里的日志,别的可以,时间不行)
--db.getCollection('location').group({ "key" : { "trip" : 1} , "$reduce" : "function(doc,prev){prev.num++}" , "initial" : { "num" : 0} , "ns" : "location" , "cond" : { "time" : { "$gte" : { "$date" : "2017-08-30T16:00:00.000Z"}}}})
--db.getCollection('location').group({ "key" : { "trip" : 1} , "$reduce" : "function(doc,prev){prev.num++}" , "initial" : { "num" : 0} , "ns" : "location" , "cond" : { "trip" : { "$gte" : "201708140000000000000"}}})
#分组扩展
db.getCollection('location').group({
key:{trip:true},
initial:{speed:0},
$reduce:function(doc,prev){
if(prev.speed<=doc['speed']){
prev.speed=doc['speed']
}
},
condition:{
$where:function(){
return this.trip >='201708300000000000000'
}
}
});
对应python代码
locations=db.location.group({'trip':True},{'time':{'$gte':start}},{'speed':0},"function(doc,prev){if(prev.speed<=doc['speed']){prev.speed=doc['speed']}}") |
======mongo地理位置查询================
查询半径多少公里内的结果集,比如附近商家查询,附件兴趣点查询
db.login.createIndex({“location”:”2d”})
数据:
{
"_id" : ObjectId("5b737ed15f14f928ca76abe9"),
"provice" : "湖北省",
"city" : "潜江市",
"area" : "总口管理区",
"lon" : "112.89",
"lat" : "30.2581",
"loc" : [
112.89,
30.2581
],
"distance" : 139817.192166838
}
语句:
db.cityname.find({area:{$ne:''},loc:{$near:{$geometry:{type:"Point",coordinates:[114.307344,30.546536]},"$maxDistance":50000}}})
db.cityname.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ 114.307344,30.546536 ] },
distanceField: "distance",
spherical: true,
maxDistance:1000000,
query:{area:{$ne:''}},
num:500
}
}
,{$match:{distance:{$ne:0}}},{$skip:100},{$limit:50}])
博文最后更新时间:
评论
-
暂无评论