小编典典

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

go

我具有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"`}

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

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"}

总结我需要按Text“房间”文档中嵌套对象中的字段搜索消息。

PS对不起,可能会出现错误,英语不是我的母语。

更新

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


阅读 243

收藏
2020-07-02

共1个答案

小编典典

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

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

$unwind消息(将messages数组转换为object)在房间里。

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

$group将消息对象放回到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)
2020-07-02