MongoDB随笔

创建用户
db.createUser({user: "abc",pwd: "abc123",roles: [ { role: "readWrite", db: "test" } ]});
db.system.users.remove({user:"abc"})
 
MongoDB导出数据
mongoexport -d service -c speech -o file --type csv -f id,time
mongoexport -d service -c speech -o file --type json -f id,time
 
mongoexport -d service -c speech -o file.json --type json -f id,time -q '{"time": {$gt:1483200000000}}' #大于等于2017年
mongoexport -d service -c speech -o file.csv --type csv -f id,time -q '{"time": {$gt:1483200000000}}' #大于等于2017年
 

建立全文索引
db.imooc_collections.ensureIndex({article:"text"})
db.imooc_collections.ensureIndex({"$**":"text"})

db.imooc_collections.find({$text: {$search: "aa"}})
db.imooc_collections.find({$text: {$search: "aa bb cc"}}) 或查询
db.imooc_collections.find({$text: {$search: "aa bb -cc"}}) 排除cc查询
db.imooc_collections.find({$text: {$search: ""aa" "bb" "cc"}}) 且查询

相似度排序
db.imooc_collections.find({$text: {$search: "aa bb"},{score: {$meta: "textScore"}}})
db.imooc_collections.find({$text: {$search: "aa bb"},{score: {$meta: "textScore"}}}).sort({score: {$meta: "textScore"})

 MongoDB更新字段及其子字段

collection.update({'account_id': field[0].strip()}, {"$set":{'account_id': field[1].strip(), "waibu":"waibu2", "person_info.account_id": field[1].strip()}},False,True)

数据源为:

{
    "_id" : ObjectId("591dc17c10a5664726235e70"),
    "account_id" : "5A76F4CAFD5771C98659D6982DA34BF0",
    "waibu" : "waibu2",
    "person_info" : {
        "account_id" : "5A76F4CAFD5771C98659D6982DA34BF0",
        "test" : "abc"
    }
}

MongoDB实现groupby count操作

db.l2.aggregate([{$group : {_id : "$account_id", num_tutorial : {$sum : 1}}}])

MongoDB实现groupby avg操作

db.speech.aggregate([{$group:{_id:"$domain",avger:{$avg:"$time"}}}])

MongoDB实现单字段分段查询:

db.client_agent.find({"time":{'$gte':1497888000000,'$lt':1497974400000}}).count()

MongoDB实现and操作

db.speech.find({"$and":[{"time":{'$gte':1497283200000,'$lt':1497369600000}},{"province":"西藏"}]}).pretty().count()

MongoDB实现distinct操作

db.speech.distinct('city',{"time":{"$gte":1498147200000}})

MongoDB实现count(distinct city)操作

db.runCommand({"distinct":"speech","key":"city","query":{"time":{"$gte":1498147200000}}}).values.length

待续。。。

原文地址:https://www.cnblogs.com/zhzhang/p/6758846.html