简体   繁体   中英

How do I query “Timestamp() or Date()” with MongoTemplate to MongoDB?

I use MongoTemplate to handle MongoDB

I want update documents' column to current time

In Mongodb command-line client, it will work with

db.collectionName.update({_id:1}, {timeCol: new Timestamp()}); or db.collectionName.update({_id:1}, {timeCol: new Date()});

But I don't know how I do that by using mongoTemplate.

Update update; update.set("timeCol", "new Timestamp()"); // of course, it doesn't work

Plz help me

Build current timestamp as

Date currentDate = new Date();
Timestamp timeStamp = new Timestamp(currentDate.getTime());

Then update collection like this :

Query query = new Query();
query.addCriteria(Criteria.where("_id").is(1));

Update update = new Update();
update.set("timeCol", timeStamp);

mongoOperations.updateFirst(query, update, "collectionName");

Update Collection like this from Spring-data-mongodb 1.6 version, this will use MongoDb current Date

Query query = new Query();
query.addCriteria(Criteria.where("_id").is(1));

Update update = new Update();
update.currentDate("timeCol")

mongoOperations.updateFirst(query, update, "collectionName");

If you want Timestamp use update.currentTimestamp(key); instead of update.currentDate(key)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM