按日期统计数量
createTime字段是Mongo中的Date类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| db.col.aggregate([ { '$group': { '_id': { '$dayOfYear': '$createTime' }, 'count': { '$sum': 1 } } }, { '$sort': { '_id': -1 } } ])
|
输出如下,_id 表示一年的第几天,353表示是一年的第353天:
1 2 3 4 5
| [ { _id: 353, count: 41 }, { _id: 352, count: 385 }, { _id: 351, count: 221 }, { _id: 350, count: 241 } ]
|
新增一个字段,使用已有字段的值
创建collection
1 2 3 4
| db.user.insertMany([ { _id: 1, name: "Maya" }, { _id: 2, name: "Ryan" } ])
|
添加 real_name 字段,值和 name 字段一样
1 2 3 4 5 6 7 8
| db.user.aggregate([ { $set: {"real_name": "$name"} }, { $out: "user" } ])
|
按中文排序
golang
1 2 3 4 5 6
| opt := &options.FindOptions{ Sort: bson.M{"name": 1}, Collation: &options.Collation{Locale: "zh"}, } f := bson.M{} cur, err := coll.Find(ctx, filter, opt...)
|
javascript
1
| db.coll.find({}).collation({"locale": "zh"}).sort({name:1})
|
备份和恢复(使用docker镜像)
1
| docker run -it --rm mongo sh -c 'mongodump --uri="mongodb://username:password@host:port/db" --collection coll --archive' > db_coll.dump
|
使用docker搭建单节点集群
在节点正常启动后做如下配置:
1 2 3 4 5
| rs.initiate()
cnf=rs.config() cnf.members[0].host="locahost:27017" rs.reconfig(cnf)
|