I am trying to $match my list of Event before to $group them but it does not work. If I remove the first $match
, I get results.
The Event has a start_date property.
I need to get the IDs of the duplicated events that start from 2 months to now. A duplicated event is an event that is a the same location at same hour.
// Create the pipeline
pipeline := []bson.M{
bson.M{
"$match": bson.M{
"start_date": bson.M{"$gt": time.Now().AddDate(0, -2, 0)},
},
},
bson.M{
"$group": bson.M{
"_id": bson.M{
"_location_id": "$_location_id",
"start_date": "$start_date",
},
"docs": bson.M{"$push": "$_id"},
"count": bson.M{"$sum": 1},
},
},
bson.M{
"$match": bson.M{
"count": bson.M{"$gt": 1.0},
},
},
}
Am I missing something ?
I checked in database and I do have events that have a start_date
matching my criteria, with that request db.events.find({}).sort({ "start_date": -1}).limit(1);
and that one db.events.find({"start_date": { "$gt": ISODate("2019-05-16T00:00:00.0Z")}}).limit(1)
Version : MongoDB shell version v3.4.6
I checked in database and I do have events that have a start_date matching my criteria, with that request
MongoDB stores time in UTC by default, and will convert any local time representations into this form.
This means, if you are in UTC+2
timezone, your query filter is by default would be in local time but the documents in the database is in UTC. You need to convert your time
to UTC. For example, you have the following documents in a collection:
{ "start_date": ISODate("2019-05-27T00:00:00Z"), "location_id": 1 },
{ "start_date": ISODate("2019-05-28T00:00:00Z"), "location_id": 2 },
{ "start_date": ISODate("2019-05-24T00:00:00Z"), "location_id": 1 },
You can perform $match
for dates two months ago as below:
pipeline := mongo.Pipeline{
{{"$match", bson.D{
{"start_date", bson.D{
{"$gt", time.Now().AddDate(0, -2, 0).UTC()},
},
},
}}},
}
cursor, err := collection.Aggregate(context.Background(), pipeline)
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
var doc bson.M
err := cursor.Decode(&doc)
if err != nil {
log.Fatal(err)
}
fmt.Println(doc)
}
Note the conversion to UTC
after the calculation. If today is already the 24th July 2019, then the query will not matched the third document. Instead you need to query with 2 months and 1 day ago.
Another tip is you can debug the date sent to the server by printing the pipeline
, i.e:
fmt.Println(pipeline)
// [[{$match [{start_date [{$gt 2019-05-24 05:19:47.382049 +0000 UTC}]}]}]]
If you have a static date value, you can also construct the date (still in UTC) as below example:
filterDate := time.Date(2019, 5, 24, 0, 0, 0, 0, time.UTC)
pipeline := mongo.Pipeline{
{{"$match", bson.D{
{"start_date", bson.D{
{"$gt", filterDate},
},
},
}}},
}
fmt.Println(pipeline)
All of the snippets above are written for MongoDB Go driver v1.0.x.