英文:
How to pass an int slice to "$in" using mgo
问题
我在使用mgo
的bson
功能创建查询时遇到了一些问题。我只是想执行{ 'search_id': { '$in': [1,2,4,7,9]}}
,但我不知道如何在mgo
中实现。
我有一个int
的切片,并尝试直接传递它:
toRemove := []int{1,2,4,7,9}
err = coll.Remove(bson.M{"search_id": bson.M{"$in": toRemove}})
我看到另一篇帖子建议我需要使用[]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}})
我已经查看了文档和其他问题,但大多数涉及切片的问题似乎是关于将数据放入切片而不是我想要实现的内容。
非常感谢任何帮助。
英文:
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
.
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}})
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}})
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.
Any help would be most appreciated.
答案1
得分: 5
你的原始提案(传递一个[]int
值)没有问题,这样做是有效的。
问题在于你使用了Collection.Remove()
,它会查找并删除与提供的选择器文档匹配的单个文档。因此,你提出的解决方案将删除恰好一个文档,其search_id
包含在你传递的切片中。如果没有找到这样的文档(并且会话处于安全模式,请参见Session.SetSafe()
),将返回mgo.ErrNotFound
。
相反,使用Collection.RemoveAll()
,它会查找并删除与选择器匹配的所有文档:
toRemove := []int{1,2,4,7,9}
info, err := c.RemoveAll(bson.M{"search_id": bson.M{"$in": toRemove}})
if err != nil {
log.Printf("删除失败:%v", err)
} else {
log.Printf("已删除 %d 个文档。", info.Removed)
}
英文:
Your original proposal (passing an []int
value) has no flaws, it's valid to do that.
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.
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论