MongoDB 简单的操作

用了MongoDB有段时间了 ,一直都是在项目中用,今天总结下在数据库中的各种操作

查询

根据条件查询

db.getCollection('Message').find({"ServerId" : 3326})

多条件查询

db.getCollection('MuteAudit').find({"GameId":2109,"Unit" : 1000,"RoleId" : 723129})

查找 物品ID大于2的数据    $gt – greater than >

db.getCollection('Goods').find({GoodsId:{'$gt':2}})


查找物品id大于等于2的数据 $gte – gt equal >=

db.getCollection('Goods').find({GoodsId:{'$gte':2}})

查询物品ID小于6 $lt – less than <

db.getCollection('Goods').find({GoodsId:{'$lte':6}})

查询物品ID小于等于6的数据  $lte – lt equal <=

db.getCollection('Goods').find({GoodsId:{'$lte':6}})

查询物品ID包含6的数据 $ne – not equal !=

db.getCollection('Goods').find({GoodsId:{'$ne':6}})

查询物品ID等于6的数据 $eq – equal =

db.getCollection('Goods').find({GoodsId:{'$eq':6}})

查询指定区间的数据

db.getCollection('Goods').find({GoodsId:{'$gte':1,'$lte':6}})

查询某个时间段内的记录

db.getCollection('Message').find({"CreateTime" : { "$gte" : ISODate("2017-08-20T00:00:00Z")
, "$lt" : ISODate("2018-08-21T00:00:00Z")}})

查询某个字符串中包含某些字符  使用 regex

db.getCollection('MuteAudit').find({"GameId":2109,"Unit" : 1000,"ActionType" : 1,"Reason" : {$regex:/自动禁言}})

查询Module(字段名)以  “英开” 头的数据

db.getCollection('Goods').find({"Module": /^英/})

查询指定列GoodsId GoodsName数据

db.getCollection('Goods').find({},{GoodsId:1,GoodsName:1});  

查询指定列 GoodsId GoodsName 数据, GoodsId>= 1 GoodsId<=6

db.getCollection('Goods').find({GoodsId:{'$gte':1,'$lte':6}},{GoodsId:1,GoodsName:1});  

按照GoodsId 排序 1 升序 -1 降序

db.getCollection('Goods').find().sort({GoodsId : 1}); 
db.getCollection('Goods').find().sort({GoodsId : -1});

db.getCollection('Goods').find().sort({"GoodsId ":-1,'_id':1})

查询 GoodsName = 时之晶 GoodsId=  40039 的数据

db.getCollection('Goods').find({"GoodsId" : 40039, "GoodsName ":"时之晶"}); 

关键字 or 查询 

db.getCollection('Goods').find({$or:[{GoodsId: 1}, {GoodsId:5}]});

关键字limit 查询前5条

db.getCollection('Goods').find().limit(5);

关键字skip 查询后10条

db.getCollection('Goods').find().skip(10)

根据条件统计数据

db.getCollection('Goods').find().count();

更新

更新一条数据

 db.getCollection('Message').update({"ServerId" : 3326},{$set:{"Content" : "888888888"}})

多条件 批量更新多条数据

db.getCollection('MuteAudit').find({"GameId":2109,"Unit" : 1000,"RoleId" : 723129}).forEach(
   function(item){                
       db.getCollection('MuteAudit').update({"_id" : item._id},{$set:{ "ActionType":0}})
   }
)

删除

删除指定列数据

db.getCollection('Goods').remove({"_id" : 1});

统计ClanID重复次数,-id代表ClanId

db.getCollection('ClanData').aggregate([
    { $group: {_id:'$ClanId', count: { $sum:1}}},
    { $match: {count: { $gt : 1}}}
    ])

  统计某个时间段内的数量

db.getCollection('Message').find({"SendTime":{"$gt":ISODate("2019-10-16T00:00:00.303Z"),"$lte":ISODate("2019-10-17T00:00:00.303Z")}}).count()

查询某个时间段内的数据

db.getCollection('Message').find({"SendTime":{"$gt":ISODate("2019-10-16T00:00:00.303Z"),"$lte":ISODate("2019-10-17T00:00:00.303Z")}})

 

原文地址:https://www.cnblogs.com/shiyilang398/p/11368214.html