Need to fetch all data rows from my collection("data") with my ID and date range as below
Date start = new Date(01/4/2022);
Date end = new Date(30/4/2022);
fStore.collection("data").whereEqualTo("ID", userId).where("date", ">=",start ).where("date", "<=", end).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
But its complaining using 2 where clauses
solution which helped me is using .whereGreaterThanOrEqualTo("date", "01/5/2022").whereLessThanOrEqualTo("date", "31/5/2022").
Related
I am a newbie to MongoDB and having a hard time querying documents with simple filtering. I would like to ask if what is the equivalent of CAST(datetime AS DATE) of mysql in MongoDB?
here's my code.
"inspection": {"hourbeg": "2020-11-23 10:12:20"}
Bson filters = Filters.and(new BasicDBObject("center.code", code),
new BasicDBObject("inspection.hourbeg", transactionDate));
Bson sorts = Sorts.descending("printedOn");
List<Document> vehicles = collection.find()
.sort(sorts)
.filter(filters)
.into(new ArrayList<Document>());
Im still trying to understand this Aggregate in MongoDB.
Never mind guys, I was able to solve my problem using this method. Might be useful for others as well.
String startDate = transactionDate.toString()+" 00:00:00";
String endDate = transactionDate.plusDays(1).toString()+" 00:00:00";
Bson gt = Filters.gt("inspection.hourbeg", startDate);
Bson lt = Filters.lt("inspection.hourbeg", endDate);
Bson andDate = Filters.and(gt, lt);
Bson filters = Filters.and(new BasicDBObject("center.code", code),
andDate);
Bson sorts = Sorts.descending("printedOn");
List<Document> vehicles = collection.find()
.sort(sorts)
.filter(filters)
.into(new ArrayList<Document>());
I want to query Cloud Firestore data in last 7 days. I am using server timestamp of Firestore also storing the time in millis.
CollectionReference IOTransactions = db.collection(userID)
.document("userData").collection("StockTransactions");
Query transactionsQuery = IOTransactions.orderBy("timestamp",Query.Direction.DESCENDING);
transactionsQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w("FirestoreDemo", "Listen failed.", e);
return;
}
for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
if (doc.get("timestamp") != null)
transactionsList.add(doc.toObject(StockTransaction.class));
Log.d("Firestore", "Added item");
}
if(transactionsList.size() < 1 )
emptyTransactionsPage.setVisibility(View.VISIBLE);
Log.d("Firestore Reading", "Successfully fetched");
adapter.notifyDataSetChanged();
pb.setVisibility(View.INVISIBLE);
}
});
How can I query the data created in last 7 days?
I am using server timestamp of Firestore also storing the time in milliseconds.
So if you are storing the timestamp in milliseconds, you are doing it wrong.
How can I query the data created in last 7 days.
To be able to query your database according to a periode of time, your timestamp property should be o type Date and not long. To see how you can achieve this, please take a look at my answer from this post.
Once you have the property set correctly, a query that looks like this should do the trick:
IOTransactions.whereLessThan("timestamp", now).whereGreaterThan("timestamp", sevenDayAgo);
In which now and sevenDayAgo are two Date objects representing the present time and a moment in time seven days ago.
According to My Knowledge you can also use the following query to get the result
Query query = mdb.collection("$YOUR_COLLECTION_NAME").orderBy("$YOUR_FIELD")
.whereGreaterThan("$YOUR_FIELD",$Begin_Date_Object)
.endAt($YOUR_DATE_OBJECT);
Note: You need to declare a Java.Util.Date object to endAt field and
orderBy must be always before startAt() or endAt() method.
The end at searches all documents containing the end at value of field in orderBy
I already can execute the desired query on mongoshell, but i need to make the same query using Java and MongoOperations.
I have checked this question, which is very similar, but it only has one condition, as mine has two and uses the $gte and $lt operators. Here's the working mongo Query:
db.getCollection('example').update({"idVar": "desiredValued"}, { $pull: { "listaHoras": { $gte: ISODate("2016-11-06T05:50:00.000Z"), $lt: ISODate("2016-11-06T06:30:00.000Z")}}})
Sample doc:
"_id" : ObjectId("58221b4610a3c71f1894ce75"),
"idVar" : "56b11259272f5515b05d70bc",
"date" : ISODate("2016-11-06T03:00:00.000Z"),
"listaHoras" : [
ISODate("2016-11-06T05:40:00.000Z"),
ISODate("2016-11-06T06:30:00.000Z"),
ISODate("2016-11-06T06:40:00.000Z")
]
Where i'll have the ISODATE as a Date variable in Java, and the desiredValue as a String variable.
So far, i have i did the following, using the previously mentioned question as example:
BasicDBObject match = new BasicDBObject("idVar", desiredValue); // to match your document
BasicDBObject update = new BasicDBObject("listaHoras", new BasicDBObject("itemID", "1"));
coll.update(match, new BasicDBObject("$pull", update));
But, as you can see, this is NOT equivalent to the desired query. Since the match for the $pull is matching "itemID"with "1". I do not know, nor was i able to find how to properly use the $gte and $lt on the same query. Neither on how to use just one or both of them. I know it CAN be done as seen on the MongoOperatioons API which says:
"update - the update document that contains the updated object or $ operators to manipulate the existing object."
Anyone knows how it can be done? And if the Date type in Java matches the ISODATE on the Mongo?
I managed to find a solution. It is similar to what Veeram posted as a answer but it's slightly different. I simply removed his updateCriteria and used a BasicDBObject in it's place.
Here's how the full code looks:
Query findQuery = new Query();
Criteria findCriteria = Criteria.where("idVar").is(idVar);
findQuery.addCriteria(findCriteria);
Update update = new Update().pull("listaHoras", new BasicDBObject( "$gte", start).append("$lte", end));
mongoOps.updateMulti(findQuery, update, "CollectionName");
Where start and end are Date variables recieved by the method. Also important to note that Mongo uses the UTC as default timezone, so we must properly format the time in order for it to remove the desired values.
You can try something like below. This will remove the two items from the listaHoras array.
Query findQuery = new Query();
Criteria findCriteria =
Criteria.where("idVar").is("56b11259272f5515b05d70bc");
findQuery.addCriteria(findCriteria);
LocalDate startDt = LocalDate.of(2016, 11, 6);
LocalTime startTm = LocalTime.of(5, 40, 0);
LocalDate endDt = LocalDate.of(2016, 11, 6);
LocalTime endTm = LocalTime.of(6, 35, 0);
Date start = Date.from(LocalDateTime.of(startDt, startTm).toInstant(ZoneOffset.UTC));
Date end = Date.from(LocalDateTime.of(endDt, endTm).toInstant(ZoneOffset.UTC));
Query updateQuery = new Query();
Criteria updateCriteria =
Criteria.where(null).gte(start).lt(end);
updateQuery.addCriteria(updateCriteria);
mongoOperations.updateMulti(findQuery, update, "example");
I have a google sheet, Where there is a column as date which stores date in dd-MM-yyyy format. Using java i am trying to fetch records with a specific date for example i want records of 14/01/2016. I have tried below code.
URL listFeedUrl = new URL(worksheet.getListFeedUrl().toString());
ListQuery listQuery = new ListQuery(listFeedUrl);
listQuery.setSpreadsheetQuery("date==\"14/01/2016\""); // Not working.
//listQuery.setSpreadsheetQuery("broadcastsubject==\"3-Minute Belly Tightening Trick\""); //Working fine.
System.out.println(listQuery.getSpreadsheetQuery());
ListFeed listFeed = googleService.getFeed(listQuery, ListFeed.class);
System.out.println(listFeed.getStartIndex());
System.out.println(listFeed.getTotalResults());
for (ListEntry row : listFeed.getEntries()) {
System.out.println(row.getCustomElements().getValue("Date")+"=================="+report.getDate());
System.out.println(row.getCustomElements().getValue("BroadcastSubject"));
}
I have tried with broadcastsubject column name which is working perfectly, it gives me number of rows. but when i tried with date field it gives me 0 rows. Can anyone please tell me how to do this with date field....!!!
I am wondering how I can search between by dates in Hibernate Search using Range-Query or is there any filter I have to implement.Following is my field in Record Entity
/**
* When the analysis started.
*/
#Temporal(TemporalType.TIMESTAMP)
#Field(index = Index.UN_TOKENIZED)
#DateBridge(resolution = Resolution.MILLISECOND)
private Date startTS;
My requirment is to find the records analysed between a two dates eg. 11/11/2011 to 11/11/2012.I am confused how to do this.
You should use a range query using from and to.
query = monthQb
.range()
.onField( "startTS" ).ignoreFieldBridge()
.from( DateTools.dateToString( from, DateTools.Resolution.MILLISECOND ) )
.to( DateTools.dateToString( to, DateTools.Resolution.MILLISECOND ) ).excludeLimit()
.createQuery();
The ignoreFieldBridge is needed since you create the string based search string yourself using DateTools.