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 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备