mongo日常操作备忘

修改

普通修改

插入数据:

db.students.insert({
 "name":"swrd",
 "age":32,
 "grade":"1.1",
 "gender":"man"
})

修改name为swrd的age的值为40:

db.students.update({"name":"swrd"},{$set:{age:40}})

修改嵌套集合中的值

插入数据:

db.students.insert({
 "name":"swrd",
 "age":32,
 "grade":"1.1",
 "gender":"man",
 "score":{
     "English":34,
     "Math":56,
     "Chinese":89
     }
})

修改swrd的数学成绩:

db.students.update({"name":"swrd"},{$set:{"score.Math":90}})

分组操作

db.test.aggregate([
	{$match:{pay_status:1}},
	{$group:
		{_id:"$player_id", total:{$sum:"$price"}}},
                {$sort:{"total":-1}}
])

上面是安装player_id分组,统计每个player_id的充值总和,然后按照充值大小降序排序。

查询

某段时间范围内的数据

db.things.find({"createTime":{"$gt":"2014-10-29 0:0:0"}}) // 大于某个时间
db.things.find({"createTime":{"$lt":"2014-10-29 0:0:0"}}) // 小于某个时间
db.things.find({"$and":[{"createTime":{"$gt":"2014-10-29 0:0:0"}},{"createTime":{"$lt":"2014-10-29 0:0:0"}}]}) // 某个时间段

嵌套属性的查询

db.customer.findOne({"login_user.phone":"110"})

phone是login_user的一个属性。

查询某个字段是否存在

查询course表中,存在lectures_count字段的记录信息

db.course.find( { "lectures.lectures_count": { $exists: true } } )
--删除course表中,所有的lectures.lectures_count字段
db.course.update({},{$unset:{"lectures.lectures_count":""}},{multi:true})

mongodb查询数字开头的集合

test:PRIMARY> show tables;
123abc
test
test_1
test_2
test_3
test_4
--查询123abc表
test:PRIMARY> db["123abc"].find()
{ "_id" : ObjectId("58b66d20aa82ef619b3ac109"), "id" : 1 }

用mongoexport 导出 -c 指定不会报错

mongoexport -d swrd -c 123abc --csv -f userId,time -o 123abc.csv

类型转换

下面这张表是BSON TYPE及他们对应的数字
此处输入图片的描述
下面的语句的目的是将total_iap字段为double的转换成int

db.basic.find({"game_info.total_iap":{$type:1}}).forEach(function(x){x.game_info.total_iap=NumberInt(x.game_info.total_iap);db.basic.save(x)})

求最大值最小值

并没有发现MongoDB有专用的求最大值的方法,不过可以通过排序和取第一条来代替。
下面的集合数据如下:

{ "_id" : ObjectId("54c39358acace71b1bd20a70"), "epoch_min" : NumberLong(1422030840), "usage_ratio" : 0.035140007734298706 }
{ "_id" : ObjectId("54c39358acace71b1bd20a71"), "epoch_min" : NumberLong(1422030900), "usage_ratio" : 0.025494230911135674 }
{ "_id" : ObjectId("54c39358acace71b1bd20a72"), "epoch_min" : NumberLong(1422030960), "usage_ratio" : 0.015415809117257595 }
mongodbCluster3:PRIMARY> db.cpu_data.find().sort({"usage_ratio":-1}).limit(1)
{ "_id" : ObjectId("54c39abbacace71b1bd599ac"), "epoch_min" : NumberLong(1422039660), "usage_ratio" : 0.5287633538246155 }
mongodbCluster3:PRIMARY> db.cpu_data.find().sort({"epoch_min":1}).limit(1)
{ "_id" : ObjectId("54c39358acace71b1bd20824"), "epoch_min" : NumberLong(1422028800), "usage_ratio" : 0.053253963589668274 }
原文地址:https://www.cnblogs.com/xiaoyuxixi/p/13803161.html