1.为集合中的每个文档添加update_time字段,内容为时间戳。
db.collection.update({}, {$set: {update_time:ISODate().valueOf()}}, {multi: true})
再删掉这个字段:
db.collection.update({},{$unset:{update_time:""}},false, true)
2.找出给定键的所有不同的值
db.collection.distinct("num")
3.分组;查询文档内容;排序;分页 (加最后一个参数查看执行状态):
db.collection.aggregate( [
{ $match: {school:'school_A'}}, //过滤出school_A的学生
{ $sort: {"age":-1}}, //按年龄倒叙排列
{ $group:
{class:"class", documents:{$push: "$$CURRENT"}}
}, //按class字段分组,输出文档信息
{ $skip:5}, //跳过5个文档
{ $limit:5} //显示5个文档内容
],
{explain:true}
)
4.求分组后的组数:
db.collection.aggregate([
{$group: {class:"class"}},
{$count:'count'}
])
5.对于这样的文档结构:
{
"_id" : ObjectId("58f0789ba9ed5d3167111292"),
"name" : "David",
"grades_list" : [
{
"subject" :"Chinese",
"grades" : 95
},
{
"subject" :"Math",
"grades" : 96
}
],
}
想要改变语文成绩为100,可以这么写:
db.collection.update({'grades_list.subject':'Chinese'},{$set:{''grades_list.$.grades':'100'}},false,true);
6.查看执行状况:
db.collection.find({}).explain("executionStats")
7.索引三连:
a.创建索引:
db.collection.ensureIndex({update_time:-1}{name:'update_time'})
b.查看索引:
db.collection.getIndexes()
c.删除索引:
db.collection.dropIndex("INDEX-NAME")
db.collection.dropIndexes()