I’m “playing” with MongoDB and Go. I am trying to read a document using FindOne() and sort on an field which is part of a nested array-object…
As you may see, my problem is, I can’t apply the setSort on the “createdTS” attribute, which is part of the nested “comments” array - I might be doing it wrong
sample data:
[
{
"title": "First Post",
"comments": [
{
"createdTS": "2020-12-01T10:00:00Z",
"text": "Comment 1-1"
},
{
"createdTS": "2020-12-01T12:00:00Z",
"text": "Comment 1-2"
},
{
"createdTS": "2020-12-01T14:00:00Z",
"text": "Comment 1-3"
}
]
},
{
"title": "Second Post",
"comments": [
{
"createdTS": "2020-12-01T10:00:00Z",
"text": "Comment 2-1"
},
{
"createdTS": "2020-12-01T12:00:00Z",
"text": "Comment 2-2"
},
{
"createdTS": "2020-12-01T14:00:00Z",
"text": "Comment 2-3"
}
]
},
{
"title": "Third Post",
"comments": [
{
"createdTS": "2020-12-01T10:00:00Z",
"text": "Comment 3-1"
},
{
"createdTS": "2020-12-01T12:00:00Z",
"text": "Comment 3-2"
},
{
"createdTS": "2020-12-01T14:00:00Z",
"text": "Comment 3-3"
}
]
}
]
GO code:
type Comment struct {
CreatedTS time.Time `bson:"createdTS"`
Text string `bson:"text"`
}
type Post struct {
ID primitive.ObjectID `bson:"_id"`
Title string `bson:"title"`
Comments []Comment `bson:"comments"`
}
data := Post{}
fields := bson.D{
{Key: "_id", Value: 1},
{Key: "title", Value: 1},
{Key: "comments", Value: bson.D{{Key: "$slice", Value: -2}}}, // -2 for the last two
}
opts := options.FindOne()
// fields ("select")
opts.SetProjection(fields)
// apply sort
opts.SetSort(bson.D{{Key: "createdTS", Value: -1}}) // i think that won't go to the comments
id, err := primitive.ObjectIDFromHex("5fc609a42b7bde6a90c78d39")
if err != nil {
fmt.Println("Invalid ObjectID")
return
}
// fetch result
err = collection.FindOne(ctx, bson.M{"_id": id}, opts).Decode(&data)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(data)