Mongodb 选择一个具有有限元素数数组的文档

Mongodb 选择一个具有有限元素数数组的文档,mongodb,go,mongodb-query,mgo,Mongodb,Go,Mongodb Query,Mgo,我有以下房间类型的结构: 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 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消息是嵌入的,它具有以下结构

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
}
这将为文件室提供给定文档中的所有消息。
问题是,我可以限制每个文档中嵌套的
消息
数组的长度吗

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

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

特别感谢@Veeram提供正确答案

基本上,您需要使用选择器。所以类似于
roomsCollection.Find(bson.M{“\u id”:room\u id})).Select(bson.M{“messages”:bson.M{“$slice”:5})。一个(room)
应该会有帮助。@Veeram嗯,我不知道$slice,但它解决了问题。非常感谢。您还可以使用使其更简单:
roomscollection.FindId(room\u id).One(…
)。