按给定字段搜索嵌套对象数组

Search array of nested objects by given field

我有以下 Room 对象结构。

type Room struct {
Id          bson.ObjectId       `json:"id" bson:"_id,omitempty"`
Title       string              `json:"title" bson:"title"`
Description string              `json:"description" bson:"description,omitempty"`
Type        string              `json:"type" bson:"type,omitempty"`
AdminId     bson.ObjectId       `json:"admin_id" bson:"admin_id"`
CreatedOn   time.Time           `json:"created_on" bson:"created_on"`
Messages    []Message           `json:"messages" bson:"messages,omitempty"`}

其中 Messages 是具有以下结构的嵌套对象数组

type Message struct {
Id      bson.ObjectId   `json:"id" bson:"_id,omitempty"`
Text        string          `json:"text" bson:"text"`
Author      Author          `json:"author" bson:"author"`
CreatedOn   time.Time   `json:"createdon" bson:"created_on"`
Reply       []Message   `json:"reply" bson:"reply,omitempty"`}

我想通过房间集合中的消息执行搜索查询。我尝试使用 "$in" 但没有帮助我。

此外,我必须通过匹配值来搜索元素。我可以使用 bson 正则表达式来做到这一点。

&bson.RegEx{Pattern: textToFind, Options: "i"}

总而言之,我需要通过 Room 文档中嵌套对象中的 Text 字段搜索消息。

P.S。抱歉可能有错误,英语不是我的母语。

更新

基本上,我想找到给定房间中包含某些子字符串的所有消息。例如,搜索房间(聊天)'A' 中包含 'some text' 子字符串的所有消息。

您可以尝试以下 mongo shell 聚合管道。

$matches 在某些房间属性上(例如 _id)。

$unwind 消息(将 messages 数组转换为对象)在房间中。

$matches 在针对 text 字段的输入正则表达式上过滤 messages.

$groups 将消息对象返回到 messages 数组。

$project 排除 _id 并仅包含 messages 用于输出。

db.collection.aggregate(
{$match:{"_id":roomid}}, 
{$unwind:"$messages"}, 
{$match:{"messages.text": { $regex: /textToFind/i } }},
{$group:{_id:null,messages:{$push:"$messages"}}}, 
{$project:{_id:0, messages:1}})

以下是未经测试的等效 mgo。

match1 := bson.M{
    "$match": bson.M{
        "_id": roomid,
    },
}

unwind := bson.M{
    "$unwind": "$messages",
}

match2 := bson.M{
    "$match": bson.M{"messages.text": &bson.RegEx{Pattern: textToFind, Options: "i"}},
}

group := bson.M{
    "$group": bson.M{
        "_id": null,
        "messages": bson.M{
            "$push": "$messages",
        },
    },
}

project := bson.M{
    "$project":  bson.M{
        "_id": 0, 
        "messages":1,
    },
}

all := []bson.M{match1, unwind, match2, group, project}
pipe := collection.Pipe(all)

result := []bson.M{}
err := pipe.All(&result)