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

标签 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 字段搜索消息。

附言抱歉可能有错误,英语不是我的母语。

更新

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

最佳答案

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

$match一些房间属性(例如 _id)。

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

$matches 在输入正则表达式上针对 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)

关于mongodb - 按给定字段搜索嵌套对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016813/

相关文章:

javascript - MongoDB 第一次不会返回正确的数据

ruby-on-rails - 如何在同一功能下为所有场景运行一次 Cucumber 后台步骤?

go - 谁能举例说明 panic 和 error 之间的确切区别以及何时在 go 中使用它们?

jquery - 使用类选择器使用Goquery解析HTML时,我在做错什么?

go - 如何在 mgo 中构造 $or 查询

go - 在 mgo 中定义 MongoDB 架构/集合

MongoDB - 在 $elemMatch 中使用 $where

MongoDB : How do the stored objects are affected by model changes?

python - 如何访问 POST 请求中嵌入的键值

多个应用服务器上的 MongoDB 连接失败