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

时间:2017-03-25 13:16:41

标签: mongodb go mgo

我有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'子字符串。

1 个答案:

答案 0 :(得分:1)

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

$match es某个房间属性(ex _id)。

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

$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)