MongoDB基礎命令總結
Mongo增刪改
根據查詢條件批次更新
> db.GoodsInfo.update({"type":1}, {$set:{"name":"birdben"}}, false, true);
刪除指定條件的資料
> db.GoodsInfo.remove({goodsStatus: 1});
查詢修改刪除
> db.GoodsInfo.findAndModify({ query: {price: {$gte: 100}}, sort: {price: -1}, update: {$set: {name: 'birdben'}, $inc: {price: 10}}, remove: true});> db.runCommand({ findandmodify : "GoodsInfo", query: {price: {$gte: 25}}, sort: {price: -1}, update: {$set: {name: 'birdben'}, $inc: {price: 10}}, remove: true});
Mongo查詢
查詢指定列(只查看name、price資料)
db.GoodsInfo.find({"_id":"123456"}, {"name":1, price: 1}}).pretty();// 當然name也可以用true或false,當用ture的情況下河name:1效果一樣,如果用false就是排除name,顯示name以外的列資訊。
distinct用法
db.GoodsInfo.distinct("name");// 對distinct結果進行篩選db.GoodsInfo.distinct("cityId", {"cityId":"330100"});
區間查詢
db.GoodsInfo.find({price: {$gte: 100, $lte: 200}});
like模糊查詢
// name中包含mongo的資料db.GoodsInfo.find({name: /mongo/});// 以mongo開頭的資料db.GoodsInfo.find({name: /^mongo/});
or查詢
db.GoodsInfo.find({$or: [{price: 100}, {price: 200}]});
exists查詢
db.GoodsInfo.find({price: {$exists: true}});// 查詢exists的個數db.GoodsInfo.find({price: {$exists: true}}).count();
查詢子文檔
db.GoodsInfo.find({"array.key":"value"});
分組查詢
// 分組查詢某一時間段,按照主貼分組,統計每個主貼的回複數量db.Postinfo.aggregate([ { $match: { "createTime":{"$gt":1443628800000, "$lt":1446436799000}, "srcPostId":{$exists:true} } }, { $group: { _id: "$srcPostId", total: { $sum: 1 } } }, { $sort: { total: -1 } }]);// 按照被拒絕的原因進行統計,每種原因的數量,並且篩選結果數量要大於等於5db.ReviewRecord.aggregate([ { $group: { _id: "$rejectReason", count: { $sum: 1 } } }, { $sort: { count: -1 } }, { $limit: 10}, { $match: { count: { $gte: 5 } } }]);// 分組之後,在進行數量的統計,統計分組後的數量大於等於5的數量有多少db.ReviewRecord.aggregate( [ { $group: { _id: { rejectReason: "$rejectReason" }, count: { $sum: 1 } } }, { $match: { count: { $gte: 5 } } }, { $group: { _id: null, count: { $sum: 1 } } }] );// 類似SQL:SELECT COUNT(*) FROM ( SELECT rejectReason, count FROM ReviewRecord GROUP BY rejectReason);// 複雜的統計計算,統計每個城市的2015-10-29的總使用者數,新使用者數,老使用者數,異常使用者數db.runCommand({ "group": { "ns":"LandPushTypeCount", "key":{"cityId":true}, "initial":{codeCount:0, newCount:0, oldCount:0, errorCount:0}, "$reduce":function(doc,prev) { prev.totalCount++; if(doc.isNew == 0) { prev.newCount++; } else { prev.oldCount++; } if(doc.isOldEquipMement == 1) { prev.errorCount++; } }, "condition":{"date":"2015-10-29", "cityId":{$in:["110000", "330100"]}} }});
參考文章: http://www.open-open.com/lib/view/open1392709240428.html http://docs.mongoing.com/manual-zh/core/single-purpose-aggregation.html http://docs.mongoing.com/manual-zh/reference/sql-aggregation-comparison.html