mongoDB使用笔记

mongoDB

#切换数据库
use database_Name

#列出数据库
show dbs

#列出collections
show collections

#查询
db.collection_Name.find({})

查询结果排序

db.collection_Name.find().sort({KEY:1})

对查询结果进行排序,需要用到sort语句,语句中需要用到排序的字段,并且使用1表示正序,-1表示逆序。

查询检索数量

db.collection_Name.find().count();

删除数据

db.col.remove({'name':'123'})

创建索引

db.collection.createIndex(keys,options)

keys:创建的索引字段 , options:1代表升序; -1代表降序, 可以创建多个字段变成复合索引

过滤检索数量

db.COLLECTION_NAME.find().sort({KEY:1}).limit(num)

批量插入

# 使用Roto 3T工具时如果要批量插入数据,可以写shell命令
for(var i=0;i<100;i++){
    db.col.insert({ 
        "timestmap" : NumberLong(1535623212000),
        ...
    })
}

去重查询

# 去重
db.consumerecords.distinct("userId")
# 对应sql
select distinct userId from consumerecords

# 加过滤条件
db.consumerecords.distinct("userId",{act:"charge"})
# 对应sql
select distinct userId from consumerecords where act="charge"

# 检索数量
db.consumerecords.distinct("userId").length
# 对应sql
select count(distinct userId) from consumerecords 

聚合查询

db.col.aggregate([
{$match:{timestamp:{$gte:1536854400000,$lt:1536897600000}}},
{$group:{_id:"$symbol",count:{$sum:1}}}}
])
db.bar_60s.aggregate([ {$match:{eob:{$gte:
1536854400000,$lt:1536897600000}}}, {$group:{_id:"$symbol",count:{$sum:1}}}, {$group:{_id:"$symbol",num:{$sum:1}}} ])

# 按照条件过滤并输出数量

  db.trade.aggregate([
    {$match:{symbol:"aaa",created_at:{$gte:1537597135000,$lt:1537597140000}}},
    {$group:{_id:"$symbol",count:{$sum:"$volume"}}}
  ])

# python中使用aggregate要用for循环输出结果
for doc in collection.aggregate(pipeline):
    print(doc) 
# python中使用sort管道 from bson.son import SON pipeline
= [ {"$unwind": "$tags"}, {"$group": {"_id": "$tags", "count": {"$sum": 1}}}, {"$sort": SON([("count", -1), ("_id", -1)])} ] import pprint pprint.pprint(list(db.things.aggregate(pipeline)))

 配置文件启动Mongo

mongod -f /etc/mongod.conf

修改数据

db.col.update(
   {'_id':ObjectId("5c07e32df65a79053ae44f74")},    --query条件
   {$set:{'create_at':'2018-12-10 13:44:30'}}       -- update得内容
)

 

posted @ 2019-02-21 23:24  EmbraceU  阅读(207)  评论(0编辑  收藏  举报