ma_jafari
ma_jafari

Reputation: 1059

MongoDB on Golang, get records that are inserted in the last 15 minutes

I'm trying to get records that are inserted in the last 15 minutes.

Although it gives me records that are inserted in the last 15 minutes, after 15 minutes passes, it still shows me records that are inserted after 15 minutes. My code:

    if len(userIds) > 0 {
        dashboardAggregations = append(dashboardAggregations, bson.M{"$match": bson.M{"_id": bson.M{"$in": userIds}}})
    }
    cursor, err = locationCollection.Aggregate(dbContext, dashboardAggregations)
    if err != nil {
        return nil, err
    }
    if len(dashboardAggregations) > 3 {
        dashboardAggregations = dashboardAggregations[:len(dashboardAggregations)-1]
    }

Following is my aggregation struct:

var dashboardAggregations = bson.A{
    bson.M{
        "$match": bson.M{
            "created_at": bson.M{
                "$gte": primitive.NewDateTimeFromTime(time.Now().Add(-15 * time.Minute)),
            },
        },
    },
    bson.M{
        "$sort": bson.M{
            "serial": -1,
        },
    },
    bson.M{
        "$group": bson.M{
            "_id":   "$userId",
            "users": bson.M{"$push": "$$ROOT"},
        },
    },
}

I appreciate any help in advance.

Upvotes: 0

Views: 283

Answers (1)

mohammad Naimi
mohammad Naimi

Reputation: 2359

create new match aggregation of checking user

bson.M{
        "$match": bson.M{
            "created_at": bson.M{
                "$gte": primitive.NewDateTimeFromTime(time.Now().Add(-15 * time.Minute)),
            },
            "user_id": "123123133123",
        },
    },

and this aggregation if user parameter don't exist

bson.M{
    "$match": bson.M{
        "created_at": bson.M{
            "$gte": primitive.NewDateTimeFromTime(time.Now().Add(-15 * time.Minute)),
        },
    },
},

Upvotes: 1

Related Questions