查询Go项目中MongoDB集合中关于对象数组的内容。

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

Query MongoDb collection regarding an array of objects in a Go project

问题

在一个Go项目中,我将一些数据存储在MongoDb的集合中,格式如下:

{
    _id: ObjectId("631f0752da589137a71687f6"),
    target: { roomId: '11' }
}

{
    _id: ObjectId("43150752da589137a71687f6"),
    target: { roomId: '12' }
}
...

我有一个目标对象数组,我想要检查数据库中是否存在一个与我的目标对象数组中的值相等的roomId

我的目标对象数组如下:

userRooms: [{"roomId":"12"}, {"roomId":"13"}, {"roomId":"14"}]

我创建一个只包含房间ID的新数组,代码如下:

var roomIds []string
for _, v := range RESPONSE.USERROOMS {
    roomIds = append(roomIds, v.ROOMID)
}

我使用以下代码进行查询:

bson.M{"target": bson.M{"roomId": bson.M{"$in": roomIds}}}

但是它不起作用,返回零个结果。

英文:

In a Go project I stored some data like this in a MongoDb Collection:

{
    _id:ObjectId("631f0752da589137a71687f6"),
    target: { roomId: '11' }
}

{
    _id:ObjectId("43150752da589137a71687f6"),
    target: { roomId: '12' }
}
.
.
.

I have a target array of objects and I want to check the database that if a roomId in database is equal to one of my array of objects values or not.

My target array of objects:

 userRooms:[{"roomId":"12"}, {"roomId":"13"}, {"roomId":"14"}]

I create a new array containing just room Id's like this:

var roomIds []string
for _, v := range RESPONSE.USERROOMS {
	roomIds = append(roomIds, v.ROOMID)
}

I do it like this:

bson.M{ "target": bson.M{"roomId":bson.M{"$in": roomIds }}}}}})

It doesn't work. it returns zero results.

答案1

得分: 2

为了构建一个嵌套字段的过滤器,使用点 . 来指定字段的完整 "路径":

bson.M{"target.roomId": bson.M{"$in": roomIds}}

其中 roomIds 应该是 ID 的切片,例如类型为 []string[]any,但它应该包含以 string 形式表示的房间 ID。

英文:

To construct a filter for a nested field, use the dot . to designate the field with its full "path":

bson.M{"target.roomId": bson.M{"$in": roomIds}}

Where roomIds should be the slice of IDs, e.g. of type []string or []any, but it should contain the room IDs as strings.

huangapple
  • 本文由 发表于 2022年9月15日 01:21:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/73720895.html
匿名

发表评论

匿名网友

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

确定