douhuang3740 2017-03-08 08:01
浏览 32
已采纳

如何使用mgo将int slice传递给“ $ in”

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 ints, 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条回答 默认 最新

  • doukuipei9938 2017-03-08 08:26
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集