dounuogong0358 2019-08-28 04:58
浏览 506

如何解决有关“过滤器”字段的问题必须是BSON类型的对象

I want to solve this problem when called find query.

This is running Golang, and use package ""gopkg.in/mgo.v2/bson".

import "gopkg.in/mgo.v2"
import "fmt"

    /* mongodb */
    info := &mgo.DialInfo{
        Addrs:    []string{1.1.1.1+ ":" + 27017},
        Database: MgName,
        Username: MgId,
        Password: MgPasswd,
    }

    mgconn, err := mgo.DialWithInfo(info)
    if err != nil {
        fmt.Printf("[ERR ] mongodb : %s
", err)
        return (-1)
    }

    /* error check on every access */
    mgconn.SetSafe(&mgo.Safe{})

    MgConn := mgconn.DB(MgName)

    col := MgConn.C("test")
    ip := "1.1.1.1"
    docs := []interface{}{
        bson.M{"message": bson.M{"$regex": bson.RegEx{`name:agent`, ""}}},
        bson.M{"message": bson.M{"$regex": bson.RegEx{ip, ""}}},
    }

    err := col.Find(docs).Sort("-time").One(&statistic)
    if err != nil {
        fmt.Printf("[INFO] mongodb select : %s
", err)
    }

This is the error message:

Failed to parse: filter: [ { message: { $regex: /name:agent/ } }, { 
message: { $regex: /192.168.18.61/ } } ]. 'filter' field must be of 
BSON type object.
  • 写回答

1条回答 默认 最新

  • doufen3091 2019-08-28 05:07
    关注

    Mongodb requires a query object but you're sending an array. I suppose you wanted to do a logical-OR of the two conditions, so try this:

    docs := bson.M{"$or": []bson.M{
        {"message": bson.M{"$regex": bson.RegEx{`name:agent`, ""}}},
        {"message": bson.M{"$regex": bson.RegEx{ip, ""}}}}}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译