如何将一个int切片传递给"$ in"使用mgo [英] How to pass an int slice to "$in" using mgo
问题描述
使用mgo
的bson功能创建查询时遇到了一些麻烦.我只是尝试做{'search_id': {'$in': [1,2,4,7,9]}}
,但是我不知道如何在mgo
中做到这一点.
I'm having a bit of trouble creating a query using the bson functionality of mgo
. I'm simply trying to do {'search_id': {'$in': [1,2,4,7,9]}}
, but I can't work out how to do it in mgo
.
我有一个int
片,并尝试直接传递它:
I have a slice of int
s, and tried passing that directly:
toRemove := []int{1,2,4,7,9}
err = coll.Remove(bson.M{"search_id": bson.M{"$in": toRemove}})
我看到了另一则帖子,提示我需要使用[]interface{}
,但这也不起作用:
I saw another post which suggested I needed to use []interface{}
, but that doesn't work either:
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上浏览了他的文档和其他问题,但是大多数涉及切片的问题似乎都是关于将数据放入切片中,而不是我要实现的目标.
I've looked through he docs and other questions here and on gh, but most questions involving slices seem to be about getting data into a slice as opposed to what I'm trying to achieve.
任何帮助将不胜感激.
推荐答案
您的原始提案(传递[]int
值)没有缺陷,这样做是有效的.
Your original proposal (passing an []int
value) has no flaws, it's valid to do that.
问题是您使用 Collection.Remove()
它会查找并删除与提供的选择器文档匹配的单个文档.因此,您建议的解决方案将删除恰好1个文档,该文档的search_id
包含在您传递的切片中.如果找不到此类文档(会话处于安全模式,请参见 mgo.ErrNotFound
.
What the problem is is that you use 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
is returned.
请使用 Collection.RemoveAll()
来查找并删除所有与选择器匹配的文档:
Instead use Collection.RemoveAll()
which finds and removes all documents matching the selector:
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)
}
这篇关于如何将一个int切片传递给"$ in"使用mgo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!