How to use $and for multiple equalities in mongodb $filter $project projection for mongodb golang driver?

54 views Asked by At

I have a collection containing documents in this structure:

type NotificationHistory struct {
    ProducedID primitive.ObjectID `json:"produced_id" bson:"produced_id"`
    For        string             `json:"notification_for" bson:"notification_for"`
    Body       string             `json:"body" bson:"body"`
    Action     string             `json:"action" bson:"action"`
    URL        string             `json:"url" bson:"url"`
    RoutesName string             `json:"routes_name" bson:"routes_name"`
    Parameter  string             `json:"parameter" bson:"parameter"`
    IsRead     bool               `json:"is_read" bson:"is_read"`
    CausedBy   uint64             `json:"caused_by" bson:"caused_by"`
    Image      string             `json:"image" bson:"image"`
    SubImage   string             `json:"sub_image" bson:"sub_image"`
    CreatedAt  time.Time          `json:"created_at" bson:"created_at"`
    UpdatedAt  time.Time          `json:"updated_at" bson:"updated_at"`
}

type UserNotificationHistory struct {
    UserID        uint                  `json:"user" bson:"user"`
    Notifications []NotificationHistory `json:"notifications" bson:"notifications"`
}

I want to filter notifications by their read status is_read and notification_for. This pipeline with multiple equalities for projection did not work, but if I just use a single equality and without $and, it works as expected.

mongo.Pipeline{
            {{"$match", bson.D{{"user", userID}}}},
            {{"$project", bson.D{
                {"user", 1},
                {"notifications", bson.D{
                    {"$filter", bson.D{
                        {"input", "$notifications"},
                        {"as", "notification"},
                        {"cond", bson.D{
                            bson.E{"$and", bson.A{
                                bson.E{"$eq", bson.A{"$$notification.notification_for", "ads"}},
                                bson.E{"$eq", bson.A{"$$notification.is_read", false}},
                            }},
                        }},
                    }},
                }},
            }}},
        },
0

There are 0 answers