需要在使用 mgo (Golang && MongoDB) 的移除中使用 $add 和 $gt

Need to use $add and $gt in remove using mgo (Golang && MongoDB)

我使用 Golang 作为我的后端,MongoDB 作为我的 Web 应用程序的数据库。我需要添加两个值并检查数据库中的值是否大于添加的值,如果是,我需要从 MongoDB.
中删除该行 我写的代码如下

err, err1 := c.RemoveAll(bson.M{
        "currenttime": bson.M{
            "$gt": bson.M{
                "$add": []interface{}{time.Now().Unix(),"100"},
            },
        },
     })

仅供参考:我为 MongoDB 编写了示例代码,但这并不能正常工作

db.Collection.remove(
   {currenttime:{
        $gt:{
                $add:[100,100]
             }
              }
    }
 )

如果可行,请告诉我。请给我任何替代方法。
谢谢

这是我的建议。您可以分两步完成,而不是一步完成。

首先找到所有符合您删除条件的条目。然后使用 remove() 查询删除那些匹配的条目。

下面的查询将 return 当前时间大于 200 的所有文档。(100 加 100)。

db.Collection.aggregate(
   [
     { $project: { currentTime: 1, current_time:{ $gt: [ "$currentTime", { $add: [ 100,100 ] } ] } }}
   ]
)

我使用以下数据创建了一个示例集合:

{ "_id" : ObjectId("57f714f0b30252798d8a2988"), "currentTime" : 1000 }
{ "_id" : ObjectId("57f714f4b30252798d8a2989"), "currentTime" : 100 }
{ "_id" : ObjectId("57f714f7b30252798d8a298a"), "currentTime" : 150 }
{ "_id" : ObjectId("57f714fcb30252798d8a298b"), "currentTime" : 1250 }

上述查询对该集合的结果是:

{ "_id" : ObjectId("57f714f0b30252798d8a2988"), "currentTime" : 1000, "current_time" : true }
{ "_id" : ObjectId("57f714f4b30252798d8a2989"), "currentTime" : 100, "current_time" : false }
{ "_id" : ObjectId("57f714f7b30252798d8a298a"), "currentTime" : 150, "current_time" : false }
{ "_id" : ObjectId("57f714fcb30252798d8a298b"), "currentTime" : 1250, "current_time" : true }

正如您从结果中看到的那样,currentTime 为 100 和 150 的文档 returned false 因为它们小于 200。

现在这是删除文档的方法 :

你在做什么:

you cannot simply use $add as this operator only works with aggregate system

你实际应该做什么

  1. 使用聚合方法获取要删除的所有记录
  2. 运行 对它们进行循环并删除

例子:

var cursor = db.Collection.aggregate([ { $match: { currenttime: { $gt:{ $add:[100,100] }}}} ]); cursor.forEach(function (doc){ db.Collection.remove({"_id": doc._id}); });

1- 如果您需要删除带有字段的行,例如time > t + 10 来自 MongoDB,你不需要 $add,你可以使用:

info, err := c.RemoveAll(bson.M{"time": bson.M{"$gt": t + 10}})
if err != nil {
    panic(err)
}

这是工作代码:

package main

import (
    "fmt"
    "time"

    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

func main() {
    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()
    session.SetMode(mgo.Monotonic, true) // Optional. Switch the session to a monotonic behavior.
    c := session.DB("test").C("Model")
    c.DropCollection()
    t := time.Now().UTC().Unix()
    err = c.Insert(
        &Model{bson.NewObjectId(), "n1", t},
        &Model{bson.NewObjectId(), "n2", t + 50},
        &Model{bson.NewObjectId(), "n3", t + 100},
        &Model{bson.NewObjectId(), "n4", t + 150})
    if err != nil {
        panic(err)
    }
    r := []Model{}
    err = c.Find(nil).All(&r)
    if err != nil {
        panic(err)
    }
    fmt.Println(r)

    info, err := c.RemoveAll(bson.M{"time": bson.M{"$gt": t + 10}})
    if err != nil {
        panic(err)
    }
    fmt.Println(info)

    r2 := []Model{}
    err = c.Find(nil).All(&r2)
    if err != nil {
        panic(err)
    }
    fmt.Println(r2)
}

type Model struct {
    ID   bson.ObjectId `json: "_id,omitempty" bson: "_id,omitempty"`
    Name string        `json: "name" bson: "name"`
    Time int64         `json: "time" bson: "time"`
}

输出:

[{ObjectIdHex("57f7354cc3176906c0ca7516") n1 1475818828} {ObjectIdHex("57f7354cc3176906c0ca7517") n2 1475818878} {ObjectIdHex("57f7354cc3176906c0ca7518") n3 1475818928} {ObjectIdHex("57f7354cc3176906c0ca7519") n4 1475818978}]
&{0 3 3 <nil>}
[{ObjectIdHex("57f7354cc3176906c0ca7516") n1 1475818828}]

2- 对于 $add,请参阅:

https://docs.mongodb.com/manual/reference/operator/aggregation/add/

根据您的示例代码,我可以观察到您使用 MongoDB remove 命令仅过滤字段 currenttime 大于特定值的值。

如果您打算在特定时间后删除某些文档,您应该查看 MongoDB Time To Live feature. Where you can Expire Data from Collections

例如,您可以指定:

db.collection.createIndex( { "field_containing_time": 1 }, { expireAfterSeconds: 3600 } )

一小时后使集合中的所有文档过期。另见 TTL Indexes

尽管此答案不包含与 Golang 相关的代码,但如果这是您在大局中尝试做的事情,它可能对您的用例有益。