英文:
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 string
s.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论