Select 一个文档,其中包含元素数量有限的数组

Select one document with array with limited number of elements

我的房型结构如下:

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

内嵌类型struct Message,结构如下

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

使用这段代码我可以提取集合的所有字段。

room := &Room{}
roomsCollection := session.DB(config.Data.DB.Database).C("Rooms")
err := roomsCollection.Find(bson.M{"_id": room_id}).One(room)
if err != nil {
    panic(err)
    return nil, err
}

这会为房间提供给定文档中的所有消息。 问题是,我可以限制每个文档中嵌套 Messages 数组的长度吗?

因此,解决方案非常简单。要执行此操作,我们可以使用 $slice。 结果查询如下:

roomsCollection.Find(bson.M{"_id": room_id})).Select(bson.M{ "messages": bson.M{ "$slice": 5} } ).One(room)

特别感谢@Veeram 的正确答案。