I have the following structure of the Room type:
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"`}
The type struct Message is embedded, which has the following structure
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"`}
Using this code I can extract all the fields of the collection.
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
}
This gives the rooms with all the messages in the given documents. The question is, can I limit the length of nested Messages
array in each document?
So, the solution was really simple. To perform this we can use $slice. The result query will be as following:
roomsCollection.Find(bson.M{"_id": room_id})).Select(bson.M{ "messages": bson.M{ "$slice": 5} } ).One(room)
Special thanks to @Veeram for correct answer.