Date comparison in MongoDB Filter - mongodb

I am trying to create a Filter that will that will return the rows where at least one minute has passed from the stored transactionDate. I am not getting an error but it is not returning any rows. The transactionDate is a timestamp in MongoDB and is stored as "transactionDate" : ISODate("2016-09-30T20:29:19.448Z")
Thanks! \m/ \m/
var filter = Builders<MyDocument>.Filter.Eq("Genre", "Rock");
filter = filter & (Builders<MyDocument>.Filter.Lt(x => x.transactionDate, DateTime.Now.AddSeconds(Math.Abs(60) * (-1))));
using (var cursor = await MyCollection.Find(filter)
.Sort(Builders<MyDocument>.Sort.Ascending(x => x.artist).Ascending(x => x.rating)).ToCursorAsync())
{
// foreach...
}

The above code actually does work. I had an issue in the data causing no results to be returned. \m/ \m/

Related

data encountered at first instance of date is returned in sequelize

I wrote a query to get the data from the table where the data of today's date is to be fetched, if data for today's date isn't present, then the latest data from latest date in the past is fetched.
var db_data = await db.daily_tip({
where: { date_for_show: { [Op.lte]: payload_date }
})
where, if data encountered at the first instance which is less than the current date is fetched.
How do I modify this query to return the data as of this query
SELECT id,tip,date_for_show from daily_tip WHERE date_for_show <= '${payload_date}' ORDER BY date_for_show DESC LIMIT 1`
Just use order and limit options like this:
var db_data = await db.daily_tip({
where: { date_for_show: { [Op.lte]: payload_date },
order: [['date_for_show', 'DESC']],
limit: 1
})

How to Data Fetch using Entity Framework in dotnet core

I have a table called "UserAnswers".below screenshot contains table data
I want to get data by surveyId and group by CreatedBy column.
for an example
There is a user called "amara#gmail.com".this user contains 4 records for a SurveyId.
I want to get this like below
Answers : [
{"2"},
{"1","0","1","1"},
{"1","2","4","3"},
{"Blue"}]
But my code returns this array for every rows.I meant duplicate records returning.
Here is my code
var qstns = await (from uans in _context.UserAnswers
where uans.SurveyId == id
select new UserAnswersReturnDto
{
UserEmail = uans.CreatedBy,
Qustns = (from ans in _context.UserAnswers
where ans.CreatedBy == uans.CreatedBy
select new UserAnswersSet
{
QNo = ans.QNo,
Ansrs = JsonConvert.DeserializeObject<JArray>(string.IsNullOrEmpty(ans.Answers) ? "[]" : ans.Answers)
}).ToArray()
}).ToListAsync();
So how to solve this issue.I opened many questions for this problem,but no one answered.Please help me.Thanks in advanced
You need to actually group your data before returning:
I used LINQ Lambda notation, but it should be quite easy to translate back to query if you're so inclined:
var qstns = _context.UserAnswers.Where(uans => uans.SurveyId == id)
.GroupBy(uans => uans.CreatedBy)
.Select(grans => new UserAnswersReturnDto {
UserEmail = grans.Key,
Qustions = grans.Select(ans => new UserAnswersSet() {
QNo = ans.QNo,
Ansrs = ans.Answers
}).ToList()
} ).ToList();
I didn't have time to double-check this, but I hope it serves as a guide to help you solve your issue!
There is no group by statement in your linq query.

How to use distinct with aggregate method for mongodb

I have some conditions and a level to check while fetching records from collection using MongoDB.
For this I am using below
def cursorOutput = dataSetCollection.find(whereObject,criteriaObject)
Which is working fine. but I want to use distinct with combination to above query.
def distinctMIdList = dataSetCollection.distinct(hierarchyField,whereObject)
Above is the query for distinct. How to combine two query.
I tried below which is not working
def cursorOutput = dataSetCollection.find(whereObject,criteriaObject).distinct("manager id")
whereObject is a condition to fetch results and criteriaObject is fields to fetch.
Distinct query is giving me result with only Manager id field but I am looking for other field also(use of criteriaObject).
Finally how to combine above two query. I searched for pipeline where $distinct is not available.
Thank you.
Map function:
var mapFunction = function() {
if(/*your criteria*/) {
emit("manager_id", this.manager_id);
}
};
Reduce Function:
var reduceFunction = function(managerFiled,values){
return Array.unique(values);
}

Composite views in couchbase

I'm new to Couchbase and am struggling to get a composite index to do what I want it to. The use-case is this:
I have a set of "Enumerations" being stored as documents
Each has a "last_updated" field which -- as you may have guessed -- stores the last time that the field was updated
I want to be able to show only those enumerations which have been updated since some given date but still sort the list by the name of the enumeration
I've created a Couchbase View like this:
function (doc, meta) {
var time_array;
if (doc.doc_type === "enum") {
if (doc.last_updated) {
time_array = doc.last_updated.split(/[- :]/);
} else {
time_array = [0,0,0,0,0,0];
}
for(var i=0; i<time_array.length; i++) { time_array[i] = parseInt(time_array[i], 10); }
time_array.unshift(meta.id);
emit(time_array, null);
}
}
I have one record that doesn't have the last_updated field set and therefore has it's time fields are all set to zero. I thought as a first test I could filter out that result and I put in the following:
startkey = ["a",2012,0,0,0,0,0]
endkey = ["Z",2014,0,0,0,0,0]
While the list is sorted by the 'id' it isn't filtering anything! Can anyone tell me what I'm doing wrong? Is there a better composite view to achieve these results?
In couchbase when you query view by startkey - endkey you're unable to filter results by 2 or more properties. Couchbase has only one index, so it will filter your results only by first param. So your query will be identical to query with:
startkey = ["a"]
endkey = ["Z"]
Here is a link to complete answer by Filipe Manana why it can't be filtered by those dates.
Here is a quote from it:
For composite keys (arrays), elements are compared from left to right and comparison finishes as soon as a element is different from the corresponding element in the other key (same as what happens when comparing strings à la memcmp() or strcmp()).
So if you want to have a view that filters by date, date array should go first in composite key.

Most efficient way to return document with highest DateTime value in field

I have a lucene's index with documents - all of them contain field that stores DateTime value. What would be recommended/most efficient way to extract document with highest value. How it would look like for integer values? Of course i am assuming that values are converted to string using DateTools.DateToString or similar methods.
Elaborating on Jf Beaulac answer, an example of such code may look like the one below. Please note that 'CreatedAt' field is used to store DateTime values.
//providing query that will not filter any documents
var query = new TermRangeQuery("CreatedAt", DateTools.DateToString(DateTime.MinValue, DateTools.Resolution.MINUTE), DateTools.DateToString(DateTime.MaxValue, DateTools.Resolution.MINUTE), false, false);
//providing sorting on 'CreatedAt' and returning just one result
var createdAtSerchResults = searcher.Search(query, null, 1, new Sort(new SortField("CreatedAt", SortField.LONG, true)));
//extracting CreatedAt value from returned document
var documentWithMaxCreatedAt = searcher.Doc(createdAtSerchResults.ScoreDocs.First().Doc);
var result = DateTools.StringToDate(documentWithMaxCreatedAt.Get("CreatedAt"));
Just issue a Query with a Sort descending on your field that contains the Date.
Use a Search method that takes a Sort in parameter, like this one:
IndexSearcher.Search(Query, Filter, int, Sort)