Mongo: advanced usage
From here,
> db.adm_record_square.aggregate({$match:{mid:118117010}},{$project:{"strlen":{"$strLenBytes":"$stage"}}},{$group:{_id:null,sum:{$sum:"$strlen"}}})
Check mongo server connections by ip:
> db.currentOp(true).inprog.reduce((accumulator, connection) => { ipaddress = connection.client ? connection.client.split(":")[0] : "unknown"; accumulator[ipaddress] = (accumulator[ipaddress] || 0) + 1; accumulator["TOTAL_CONNECTION_COUNT"]++; return accumulator; }, { TOTAL_CONNECTION_COUNT: 0 })
Sometimes a tablesname is in collision with some key words. To visit such tables, use:
db.getCollection('group').find()
Mongo match, count and sort:
db.welcomer_stat.aggregate([{$match:{ct:{$gt: 1573056000,$lte:1573571701}}},{$group:{_id:"$mid",count:{$sum:1}}},{$sort:{count:-1}},{$skip:10}])
check connections:
db.currentOp(true).inprog.reduce((accumulator, connection) => { ipaddress = connection.client ? connection.client.split(":")[0] : "unknown"; accumulator[ipaddress] = (accumulator[ipaddress] || 0) + 1; accumulator["TOTAL_CONNECTION_COUNT"]++; return accumulator; }, { TOTAL_CONNECTION_COUNT: 0 })
mongo foreach usage:
# add new db.member.find({desc_ut:{$exists:1}}).forEach(function(doc){db.membr.update({_id:doc._id},{$set:{desc_ct:doc.desc_ut}})}); # 去重 db.myCollection.find({}, {type:1,objid:1,mid:1}).sort({_id:1}).forEach(function(doc){ db.myCollection.remove({_id:{$gt:doc._id}, type:doc.type, objid:doc.objid, mid:doc.mid}); })
mongodump mongorestore : used when restoring dbs in bson format, together with db metadatas.
mongoexport mongoimport : used when appending items in json format.
From here, quotes:
Hint
虽然MongoDB查询优化器一般工作的很不错,但是也可以使用hints来强迫MongoDB使用一个指定的索引。
这种方法某些情形下会提升性能。 一个有索引的collection并且执行一个多字段的查询(一些字段已经索引了)。
传入一个指定的索引,强迫查询进行使用。
db.collection.find({user:u, foo:d}).hint({user:1});
确定创建了索引。
上面的例子,首先你确定索引已经创建了。请使用ensureIndex()创建索引。其他的例子,有个在 {a:1, b:1} 上的索引,名称为"a_1_b_1":
db.collection.find({a:4,b:5,c:6}).hint({a:1,b:1});db.collection.find({a:4,b:5,c:6}).hint("a_1_b_1");强迫查询不适用索引, (做一个表的扫描), 使用:
> db.collection.find().hint({$natural:1})
Anyone is permitted to copy/use the contents and codes from this blog.
Sansna is not going to guarantee anything, Sansna will not take any responsibility of any results after using these codes/contents.
浙公网安备 33010602011771号