常用指令
# 授权 use mydb db.createUser({ user: "mydb_reader", "pwd": "abcd1234", roles: [{role: "read", db: "mydb"}]}) db.createUser({ user: "mydb_writer", "pwd": "abcd1234", roles: [{role: "readWrite", db: "mydb"}]}) # 模拟事务 db.id_inc.findAndModify({ "query": {"name": "user"}, "update": {$set: {"id": 10000}}, "new": true}) # 删表 db.id_inc.drop() # 插入 db.id_inc.insert({"name": "user", "id": 10000}) db.account.insert({ "urs": "busuncle@163.com", "account_id": 1, "user_list": []}) # 更新 db.account.update({"account_id": 1}, {"$push": {"user_id_list": 10001}}) db.user.update({"user_id": 10005}, {$set: {"exp": 10}}) db.account.update({"account_id": 1}, {"$set": {"user_list": []}}) db.user.update({},{$unset: {hero_list:1}}, false, true) db.user.update({}, {$rename: {"name1": "name2"}}, {multi: true}) db.user.update({ "user_id": "10001-2006"}, {"$set": {"hero_mgr.hero_list.10100.exp": 10}}) # 查找 db.user.find({ "user_id": "10001-2006"}, {"hero_mgr.hero_list.10100": 1}).pretty() db.user.find({"_id": {$regex:"10002-"}}, {"lv": 1}) # 删记录 db.user.remove({"_id": {$regex: "10001-10000"}}) db.user.count({"_id": {$regex: "10001-10000"}}) # 备份 db.user.find({ "_id": {"$regex": "10001-61[0-3][0-9]$"}}, null).forEach( function(doc){db.user_backup3.insert(doc);}) db.user_backup1.find().forEach(function(doc){db.user_backup2.insert(doc);}) db.user_backup.find({"_id": "10001-1"}).forEach( function(doc){db.user.remove({"_id": doc["_id"]}); db.user.insert(doc);}) # 列表 db.test1.update({"_id": 1}, {$push: {"scores": 1}}, upsert=true) db.test1.find({"_id": 1}, {"list": {"$slice": [0,3]}}) // 从第0个开始,取3个 # 集合 db.test2.update({"_id": 1}, {$addToSet: {"scores": 1}}, upsert=true) # $addToSet反向操作,从集合里remove元素 db.test2.update({"_id": 1}, {$pull: {"scores": 1}}) # 聚合例子,随机返回若干匹配条件的文档 db.mycoll.aggregate([{$match: {"num": {$gt: 10}}}, {$sample: {"size": 3}}]) # 聚会统计,按某个key(或组合key),统计doc数量 db.test.aggregate([{$group: {_id: {key1: "$key1", key2: "$key2"}, count: {$sum: 1}}}])