Mongod实用实例
注意事项(初始化失败)
- 服务器在原有数据库上开启replicaset后,没有权限rs.initiate()
- 把auth=True关掉后,再初始化,完成后在开启auth=True,即可
- 服务器用db.changeUserPassword("userName","Password")
- 把auth=True关掉后,登录root账户,进入admin数据库,更改密码,之后再打开auth=True,即可
表合并
db.content.insert(obj)
});```
### **lookup拼表**
```db.hotinfo.aggregate([{
$lookup:{
from: "topic",
localField: "hotable_id",
foreignField: "_id",
as: "topic"
}
},{
$sort:{"reach":-1}
}
])
数据库迁移
mongodump -h 111.231.92.176:29032 -u spider -p spider.1qazWSX -d spider -o ./backups/mongobak/$(date+"%m-%d-%y")
mongorestore -h 172.16.5.124:27017 -u spider -p spider.1qazWSX -d spider ./date+%m-%d-%y/spider --drop
查询和 删除指定日期的数据
# 如果日期格式为ISO格式
db.content.find({ "CreateTime" : { "$gte" : ISODate("2020-05-08T00:00:00Z")
,"$lt" : ISODate("2017-04-21T00:00:00Z") } }).count()
db.content.find({ "publish_at" : { "$gte" : ISODate("2020-05-29T00:00:00Z")} }).count()
如果日期为字符串格式
db.coll.remove({date:{$lte:new Date(2012, 7, 14)}})
查找重复数据,并去重
db.getCollection('source_weixin_test1').aggregate([{
'$group': {
'_id': {
'name': '$name',
},
'uniqueIds': {
'$addToSet': '$_id'
}
'count': {
'$sum': 1
}
}
},
{
'$match': {
'count': {
'$gt': 1
}
}
}
], {
allowDiskUse: true
}).forEach(function(doc) {
doc.uniqueIds.shift();
db.getCollection('source_weixin_test1').remove({
_id: {
$in: doc.uniqueIds
}
});
})
参考:
https://blog.csdn.net/haoyuexihuai/article/details/100084075
给用户添加数据库读写权限
db.grantRolesToUser("spider",[{role:"readWrite",db:"local"}])
表复制、表备份
db.source_weixin_test1.find().forEach(function(x){db.source.insert(x)})
删除指定字段
db.content.update({"name":{$exists:1}},{"$unset":{"name":""}},{multi:true})
设置用$set
更改字段名
db.content.update({}, {$rename:{"repost_at":"repost_count"}}, false, true)
导出csv
mongoexport -h 111.231.92.176:29032 -u spider -p spider.1qazWSX -d spider -c source_weixin --csv -o ./source_weixin.csv`
追加字符串更新数据/批量更新数据
db.getCollection("source").find({'platform':"微信"}).forEach(
function(item){ db.getCollection('source').update({"_id":item._id},{$set:{"url":"https://mp.weixin.qq.com" + item.url}})
}
);
//批量更新
var bulk = db.content1.initializeOrderedBulkOp();
var counter = 0;
db.content1.find({"repost_count": NaN}).forEach(function (data) {
var updoc = {
"$set": {}
};
var myKey = "repost_count";
updoc["$set"][myKey] = 0
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
if (counter % 1000 == 0) {
bulk.execute();
bulk = db.content1.initializeOrderedBulkOp();
}
})
if (counter % 1000 != 0) bulk.execute();
数据恢复
https://mongoing.com/archives/4158
类型转换
- string 转number
db.getCollection('content').find({"repost_count": {$type:"string"}}).forEach(**function**(x){
db.getCollection('content').updateOne({_id: x._id}, {$set:{quantity: Number(x.quantity)}})
})
db.content.find().forEach( **function** (x) {
x.repost_count = parseInt(x.repost_count);
db.content.save(x);
})
- NaN类型不能直接转int(可以把NaN和null转变为0)
- 0在mongo中是double类型
var bulk = db.content.initializeOrderedBulkOp();
var counter = 0;
db.content.find({"view_count": {$type:"string"}}).forEach(function (data) {
var updoc = {
"$set": {}
};
var myKey = "view_count";
updoc["$set"][myKey] = parseInt(data.view_count);
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
if (counter % 1000 == 0) {
bulk.execute();
bulk = db.content.initializeOrderedBulkOp();
}
})
if (counter % 1000 != 0) bulk.execute();
类型数字对应表https://docs.mongodb.com/manual/reference/operator/query/type/#_S_type
节点备份(最好再开启两个节点,如果只增一个,可能导致无法选举出primary)
- 三台服务器都安装上mongodb,并且都开启replica Set,配置好配置文件后,service mongod start后,不要进入备份的节点mongo shell中做rs.initiate()操作,初始化工作直接在primiary的mongo shell 执行
config={
_id : "rs0",
members :[
{ _id : 0 , host: "172.16.5.124:27017"},
{ _id : 1 , host: "172.16.5.137:27017"},
{ _id : 2 , host: "172.16.5.126:27017"}
]
}
rs.initiate(config)
rs.config()
rs.status()
增加优先级
config=rs.config()
config.members[0].priority=99
rs.reconfig(config)
timestamp 字符串转date类型
db.content.aggregate([
{
"$project": {
"publish_at": {
"$toDate": {
"$toLong": "publish_at"
}
}
}
}
])
//var timestamp = Timestamp(1560506685, 958);//存储的时间戳格式
//print( new Date( timestamp.t*1000+timestamp.i))//转换成日期类型
db.getCollection("content").find({'publish_at':{"$type":"string"}}).forEach(
function(item){
var a=Timestamp(parseInt(item.publish_at),958);
db.getCollection('content').update({"_id":item._id},{$set:{"publish_at":new Date(a.t*1000+a.i)}})
});
一个人可以被毁灭,但不能被打败