gpt4 book ai didi

mongodb - 需要使用 $add 和 $gt 删除使用 mgo (Golang && MongoDB)

转载 作者:IT王子 更新时间:2023-10-29 01:54:44 24 4
gpt4 key购买 nike

我使用 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]
}
}
}
)

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

最佳答案

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,参见:
Query where sum of two fields is less than given value
https://docs.mongodb.com/manual/reference/operator/aggregation/add/

关于mongodb - 需要使用 $add 和 $gt 删除使用 mgo (Golang && MongoDB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39908192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com