参考:https://blog.csdn.net/u013066244/article/details/80004153
public static void main(String[] args) {
final MongoCollection<Document> useropRecord;
//连接数据库 start
MongoCredential credential = MongoCredential.createCredential("user", "user", "user.gogoal.com".toCharArray());
ServerAddress serverAddress;
serverAddress = new ServerAddress("192.168.11.22", 22);
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
@SuppressWarnings("resource")
MongoClient mongoClient = new MongoClient(addrs, credentials);
System.out.println("Connect to database successfully");
//连接数据库 end
MongoDatabase database = mongoClient.getDatabase("user");
useropRecord = database.getCollection("userop_record");//埋点表
Document match = new Document();
match.append("_tm", null);
Date stringToDate = DateUtil.stringToDate("2018-04-01", "yyyy-MM-dd");
match.append("date", new Document("$gte", stringToDate));
useropRecord.find(match).forEach(new Block<Document>() {
int aa=3000;
@Override
public void apply(Document doc) {
Document project = new Document();
project.append("$set", new Document("_tm", new BSONTimestamp((int)(System.currentTimeMillis() / 1000), aa++)));
useropRecord.updateMany(new BasicDBObject("_id", doc.get("_id")), project);
if(aa >= 4000){
aa = 3000;
}
}
}
);
}
注意,使用BSONTimestamp或者BsonTimestamp,需要在系统时间上除以1000,因为系统给的时间是毫秒。