`$in`运算符在传入空数组时会报错。

huangapple go评论88阅读模式
英文:

$in operator gives error if pass blank array into it

问题

我在Go和MongoDb项目上工作过。在其中,我遇到了一个问题。我使用$in运算符将一个动态的整数切片([]int)传递给查询。一切看起来都很好,但当这个切片为空时,它会返回一个错误"$in需要一个数组"。但我将其用作搜索参数,并且希望如果我传递空数组,则它与所有内容匹配。

注意:我使用的是MongoDB shell版本v5.0.3

这是我的代码:

var searchedProfiles []int
searchFilter := bson.M{"customer.id": bson.M{"$in": searchedProfiles}}
newQry := []bson.M{
	{"$lookup": bson.M{
		"localField":   "cid",
		"from":         "customers",
		"foreignField": "_id",
		"as":           "customer"}},
	{"$match": searchFilter},
}

如果有人有任何想法,请告诉我。谢谢!

英文:

I have worked on the Go and MongoDb project. In which, I have faced a problem. I have passed a dynamic slice of integeres ([]int) into a query using $in operator. Every thing seems good but when this slice is empty then it return an error "$in needs an array". But i used it as a search parameter and want if i pass blank array then it matched with all.

Note: I have userd MongoDB shell version v5.0.3

Here is my code:

var searchedProfiles []int
searchFilter := bson.M{"customer.id": bson.M{"$in": searchedProfiles}}
newQry := []bson.M{
	{"$lookup": bson.M{
		"localField":   "cid",
		"from":         "customers",
		"foreignField": "_id",
		"as":           "customer"}},
	{"$match": searchFilter},
}

If anybody have any idea please let me know. Thanks!

答案1

得分: 1

nil值不会被编组为空数组,所以请确保searchedProfiles不是nil,而是至少一个空切片:

searchedProfiles = []int{}

这将被编组为一个空数组,因此您将不会收到所提到的错误。

但是这不会给您所有的文档,这将给您零个结果(空列表中没有任何内容)。

如果没有搜索到的配置文件,请从过滤中省略此部分。

英文:

nil values aren't marshaled as empty arrays, so make sure searchedProfiles is not nil but at least an empty slice:

searchedProfiles = []int{}

This will be marshaled into an empty array, so you won't get the error in question.

But this will not give you all documents, this will give you no results (nothing is in the empty list).

If there are no searched profiles, leave this out from the filtering.

huangapple
  • 本文由 发表于 2021年12月2日 18:51:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/70198085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定