Reputation: 1998
I have a collection with the following document :
{
"observation": {
"temporalExtent": [
{
"dateBeg": ISODate("2002-07-28T20:47:00.000+02:00"),
"dateEnd": ISODate("2003-09-13T16:17:00.000+02:00")
}
]
}
}
I'm trying to make the following aggregation operation that should return the document above but I can't figure out what's wrong and why the document is not found.
db.collection.aggregate({
"$match": {
"observation.temporalExtent": {
"$elemMatch": {
"dateBeg": {
"$gte": {
"$dateFromString": {
"dateString": "1892-01-05T23:50:39.000Z"
}
}
}
}
}
}
})
Any idea? You can play with this config here
The aggregation operation $dateFromString
is generated by Spring-data-mongodb DateOperators.DateFromString fromString(Object value) method. I'd like to know why I'm misusing this operator or another way to generate the same operation with $date
or ISODate
constructor as mentionned by @arsendavtyan and @mani.
Criteria.where("dateBeg")
.lte(DateOperators.DateFromString.fromString(tmpExtent.getString("fromDate")))
.lte(DateOperators.DateFromString.fromString(tmpExtent.getString("toDate")))
Upvotes: 1
Views: 1307
Reputation: 1998
Here is the workaround that prevents the use of $dateFromString
operator.
The String representation of the date are parsed into Instant
JSONObject tmpExtent = (JSONObject) item;
Instant from = Instant.parse(tmpExtent.getString("fromDate"));
Instant to = Instant.parse(tmpExtent.getString("toDate"));
The Criteria is constructed like:
Criteria.where("dateBeg").lte(from).lte(to)
And the query made to mongoDB looks like @arsendavtyan first solution.
{ "dateBeg" : { "$gte" : { "$date" : "2011-01-31T23:00:00.000Z"} , "$lte" : { "$date" : "2019-02-21T23:00:00.000Z"}}}
Upvotes: 0
Reputation: 1549
Please try running the
db.collection.aggregate([{
"$match": {
"observation.temporalExtent": {
"$elemMatch": {
"dateBeg": {
"$gte": new ISODate("1892-01-05T23:50:39.000Z")
}
}
}
}
}])
Try running using mongoshell or Robo Mongo , Mongoplayground throw error for newIsoDate()
Upvotes: 1
Reputation: 1957
Replace value.dateString
with $date
or just use ISODate
instead of String
Option 1
db.collection.aggregate({
"$match": {
"observation.temporalExtent": {
"$elemMatch": {
"dateBeg": {
"$gte": {
"$date": "1892-01-05T23:50:39.000Z"
}
}
}
}
}
})
Option 2
db.collection.aggregate({
"$match": {
"observation.temporalExtent": {
"$elemMatch": {
"dateBeg": {
"$gte": ISODate("1892-01-05T23:50:39.000Z")
}
}
}
}
})
Upvotes: 1