mongoDB(1)

1.查询时,不写条件的查询,速度要远远大于有条件的查询。

2.消除重复数据:

3.db.listCommands() 查看mongo的runCommand支持哪些功能了。

db.runCommand()  里面的参数还不一样,runCommand是非常底层的写法。

3.1db.runCommand({distinct:"logs","key":"name"})

  > db.runCommand("distinct",{"ns":"logs","key":"name"})
  {
          "values" : [ ],
          "stats" : {
                  "n" : 0,
                  "nscanned" : 0,
                  "nscannedObjects" : 0
          },
          "ok" : 1
  }
  > db.runCommand({"distinct":"logs","key":"name"})
  {
          "values" : [
                  "jj"
          ],
          "stats" : {
                  "n" : 1,
                  "nscanned" : 1,
                  "nscannedObjects" : 0,
                  "timems" : 70,
                  "cursor" : "BtreeCursor name_1"
          },
          "ok" : 1
  }

3.2db.runCommand({dropIndexes:'foo', index : {y:1}})//删除集合foo中{y:1}的索引 ,在用mongoose的时候,执行这条命令,就可以删除索引.

3.3db.runCommand({dropIndexes:'foo', index : '*'})//删除集合foo中所有的索引

重建索引

db.myCollection.reIndex()
// same as:
db.runCommand( { reIndex : 'myCollection' } )

去除重复

db.runCommand('distinct':"myCollection","key":"name")

mongoose可直接使用Query#distinct([criteria], [field], [callback])

YourModel.db.db.executeDbCommand({geoNear : "locations", near : [11.252,14.141], spherical: true }, function(err,res) { console.log(res.documents[0].results)});

mongoose,来执行runCommand命令,参考网址:http://stackoverflow.com/questions/5861134/how-to-execute-runcommand-with-mongoose

4.group 分组操作

4.1 db.runCommand({'group':{

    "ns":"students",

    "key":{"age":true},

   "initial":{"count":0},

   "condition":{"age":{"$gte":19}},   //分组条件

   "$reduce":function(doc,prev){        print(doc,prev)

         }

 }

})

在mongoose中直接使用aggregate聚合的方法,在里面搭配group分组。

Users.aggregate()
  .group({ _id: null, maxBalance: { $max: '$balance' } })
  .select('-id maxBalance')
  .exec(function (err, res) {
    if (err) return handleError(err);
    console.log(res); // [ { maxBalance: 98 } ]
});


如果计算平均值,那么使用group就很难实现了。
原文地址:https://www.cnblogs.com/jay--zhang/p/5990158.html