duanguane1670 2019-07-17 16:46
浏览 713
已采纳

如何结合bson.M过滤器

I am trying to combine some filters with no success. I am using the mongodb driver for go

// FindOneByID returns an error on fail, otherwise, it sets the {out} by the result.
func FindOneByID(collectionName string, id *primitive.ObjectID, out interface{}, considerArchivedItems bool) error {
    ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)
    var filter bson.M

    if considerArchivedItems {
        filter = bson.M{"_id": id}
    } else {
        filter = bson.M{"$and": bson.A{ bson.M{"_id": id}, bson.M{isArchived: bson.M{"$ne": false}}}}
    }

    return database.Collection(collectionName).FindOne(ctx, filter).Decode(out)
}

Now, I insert an object as archived and trying to get the document. The document is inserted as archived, so I want to consider archived items.

However, when I pass in the else, document can be either archived or not (false or true), I still get it anyway. So it means that my $and doesn’t work..

const (
    databaseNameUnitTests           = "database_name_unit_tests"
    databaseCollectionNameUnitTests = "database_name_unit_tests"
)

type Test struct {
    ID          *primitive.ObjectID `protobuf:"bytes,1,opt,name=id,proto3" json:"_id,omitempty" bson:"_id,omitempty"`
    IsArchived  bool                `protobuf:"varint,2,opt,name=IsArchived,proto3" json:"is_archived,omitempty" bson:"is_archived,omitempty"`
    Description string              `protobuf:"varint,3,opt,name=Description,proto3" json:"description,omitempty" bson:"description,omitempty"`
}

// func
    var item Test
    err := mongodb.FindOneByID(databaseCollectionNameUnitTests, insertedID, &item, false)

The following query from Robo 3T : db.getCollection('database_name_unit_tests').find({$and:[{"_id":ObjectId("5d2e8afeb0e106fbe0d5af21")},{"is_archived": {$ne:false}}]}) this works tho, where am I wrong?

  • 写回答

1条回答 默认 最新

  • doumu4916 2019-07-17 19:18
    关注

    I have a lot of trouble getting bson.A to work with $and statements, try using bson.D instead.

    bson.D{{"$and", []bson.D{
       bson.D{{"_id",id}},
       bson.D{{"isArchived", bson.D{{"$ne", false}}}},
    }}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?