How do I query "Timestamp() or Date()" with MongoTemplate to MongoDB? - 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

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)

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");

Related

Get MongoDB records of the last day in the previous month

I've a MongoDB collection that contains records with a field called createdAt, I want to get the last createdAt in the previous month of a given date using mongoTemplate aggregation in a spring boot application.
example of a record:
{
createdAt: new Date('2022-11-01'),
//other fields ...
}
Note:
Let say for 22/11/2022 given date, and we have records with createdAt fields are 12/10/2022, 22/10/2022, 27/10/2022; I wanna get the date : 27/10/2022
if you are using mongo template you could find it like this:
template.aggregate(
newAggregation(
match(Criteria.where("createdAt").lt(new Date(2022,11,01))),//<--- here you pass the month in question
project("createdAt").andExclude("_id"),
group().addToSet("createdAt").as("LATEST_DATES"),
unwind("LATEST_DATES"),
sort(Sort.Direction.DESC, "LATEST_DATES"),
limit(1),//to get only one
project().andExclude("_id")
),
"YOUR COLLECTION NAME",
DBObject.class
)
You can do that like this :
First create a date of first day of current month.
firstDayOfCurrentMonth = LocalDate.now().withDayOfMonth(1))
then use it in query:
newAggregation(
match(Criteria.where("createdAt").lt(firstDayOfCurrentMonth))),
sort(Sort.Direction.DESC, "createdAt"),
limit(1)
)

update multiple documents in mongodb from spring mongo

In my use case I want to update multiple documents at once, documents that match a query, using spring-data-mongo.
Here is what I have been trying,
Criteria filterCriteria = new Criteria().andOperator(Criteria.where("bac").is("def"));
Update update = new Update();
update.set("status", status);
Query query = new Query();
query.addCriteria(filterCriteria);
mongoOperations.findAndModify(query, update, MyClass.class);
But this is not updating any document.
Plus I have looked up in the mongo documentation but have not anything useful
https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#comparisons-with-the-update-method
Here is the version that I am using
Mongodb - 3.6
spring-data-mongodb - 1.5.5.RELEASE
findAndModify(...) method can update a document and return either the old or newly updated document in a single operation.
To update all document that matches the given query use updateMulti(...).
https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoOperations.html#updateMulti-org.springframework.data.mongodb.core.query.Query-org.springframework.data.mongodb.core.query.UpdateDefinition-java.lang.Class-
visit the link and there you will find it.
#Autowire
MongoTemplate mongoTemplate;
Query query = new Query();
Criteria filterCriteria = Criteria.where("bac").is("def");
query.addCriteria(filterCriteria);
Update update = new Update();
update.set("status", status);
mongoTemplate.updateMulti(query, update, MyClass.class);

Update entire document in mongodb using morphia

I have document which I need to update but updated parameters are not same all the time it depends on user. So how can I update document or replace whole document with new values based on id.
You wrap your updated values in a Map the set the update:
Map<String, Object> updateInfo; // Key is db column name, value is updatedValue
Then create update operations:
Query<Entity> filter = datastore.createQuery(Entity.class)
.field("_id", id);
UpdateOperations<Entity> updateOps = datastore.createUpdateOperations(Entity.class);
updateInfo.entrySet().forEach(e -> updateOps.set(e.getKey(), e.getValue());
datastore.update(filter, updateOps);
By this way, you can update entity with any number of fields

:Spring data is able to fetch data between 2 dates but not same date different times of same date

Query to fetch records for time range of 10 seconds is fetched properly in mongo shell using below:
db.getCollection('collection-name').find({"#timestamp":{"$gte": ISODate("2018-02-07T01:51:45.005Z"),"$lt": ISODate("2018-02-07T01:51:55.005Z")}});
But in spring-data-mongodb I am unable to get the data using below methods. Either I am not able to define ISODate("String value") or new Date("String value") in #Query annotation or mongo query criteria.
Method 1: Mongo Repository & Query
#Query("{'#timestamp' :{'$gte':?0, '$lt':?1}}")
public List<collection-name> findByTimestamp( Date date,Date newdate);
Method 2: Using Mongo Query with criteria
Query query = new Query();
query.addCriteria(Criteria.where("#timestamp").gte( date).lt(newdate));
where date and new date fields are:
DateFormat df=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS\'Z\'");
Date date = df.parse("2018-02-07T01:51:45.005Z");
Date newdate = df.parse("2018-02-07T01:51:55.005Z");

Bulk save to mongo db using Morphia

I have a list of data object which has to be saved in mongodb.
if datastore.save(ListofObject) is used will it degrade the performance.Morphia version is 1.1.0 and java jdk 1.8
You can do this. Suppose if entity name is User,
Query<User> query = MongoUtils.getDataStore()
.createQuery(User.class)
.filter("active", Boolean.TRUE)
.filter("suspensionDate <", new Date());
UpdateOperations<User> updateOperations = MongoUtils.getDataStore()
.createUpdateOperations(User.class)
.set("active", false);
UpdateResults updateResults = MongoUtils.getDataStore()
.update(query, updateOperations, false, null);
In the above case the all user with flag active true and suspension date less that today will be set with flag active false.
If total records updated need to know then below lines are useful.
WriteResult writeResult = updateResults.getWriteResult();
int totalRecordsUpdated = writeResult.getN();