mongo日常操作備忘
阿新 • • 發佈:2020-10-12
修改
普通修改
插入資料:
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 }