如何使用 mgo 将 int 切片传递给“$in”
How to pass an int slice to "$in" using mgo
我在使用 mgo
的 bson 功能创建查询时遇到了一些麻烦。我只是想做 {'search_id': {'$in': [1,2,4,7,9]}}
,但我不知道如何在 mgo
中做。
我有一片 int
s,并尝试直接传递它:
toRemove := []int{1,2,4,7,9}
err = coll.Remove(bson.M{"search_id": bson.M{"$in": toRemove}})
我看到另一个 post 建议我需要使用 []interface{}
,但这也不起作用:
toRemoveI := make([]interface{}, len(toRemove))
for idx, val := range toRemove {
toRemoveI[idx] = val
}
err = coll.Remove(bson.M{"search_id": bson.M{"$in": toRemoveI}})
我在这里和 gh 上浏览了他的文档和其他问题,但大多数涉及切片的问题似乎都是关于将数据放入切片而不是我想要实现的。
如有任何帮助,我们将不胜感激。
您的原始提案(传递 []int
值)没有缺陷,这样做是有效的。
问题是你用Collection.Remove()
which finds and removes a single document matching the provided selector document. So your proposed solution will remove exactly 1 document, one whose search_id
is contained in the slice you passed. If no such document is found (and the session is in safe mode, see Session.SetSafe()
), mgo.ErrNotFound
被退回了。
而是使用 Collection.RemoveAll()
查找并删除 all 匹配选择器的文档:
toRemove := []int{1,2,4,7,9}
info, err := c.RemoveAll(bson.M{"search_id": bson.M{"$in": toRemove}})
if err != nil {
log.Printf("Failed to remove: %v", err)
} else {
log.Printf("Removed %d documents.", info.Removed)
}
我在使用 mgo
的 bson 功能创建查询时遇到了一些麻烦。我只是想做 {'search_id': {'$in': [1,2,4,7,9]}}
,但我不知道如何在 mgo
中做。
我有一片 int
s,并尝试直接传递它:
toRemove := []int{1,2,4,7,9}
err = coll.Remove(bson.M{"search_id": bson.M{"$in": toRemove}})
我看到另一个 post 建议我需要使用 []interface{}
,但这也不起作用:
toRemoveI := make([]interface{}, len(toRemove))
for idx, val := range toRemove {
toRemoveI[idx] = val
}
err = coll.Remove(bson.M{"search_id": bson.M{"$in": toRemoveI}})
我在这里和 gh 上浏览了他的文档和其他问题,但大多数涉及切片的问题似乎都是关于将数据放入切片而不是我想要实现的。
如有任何帮助,我们将不胜感激。
您的原始提案(传递 []int
值)没有缺陷,这样做是有效的。
问题是你用Collection.Remove()
which finds and removes a single document matching the provided selector document. So your proposed solution will remove exactly 1 document, one whose search_id
is contained in the slice you passed. If no such document is found (and the session is in safe mode, see Session.SetSafe()
), mgo.ErrNotFound
被退回了。
而是使用 Collection.RemoveAll()
查找并删除 all 匹配选择器的文档:
toRemove := []int{1,2,4,7,9}
info, err := c.RemoveAll(bson.M{"search_id": bson.M{"$in": toRemove}})
if err != nil {
log.Printf("Failed to remove: %v", err)
} else {
log.Printf("Removed %d documents.", info.Removed)
}