I have a mongodb document which contains an array called "data". I want to be able to only get certain ranges from the array.In robo 3T I am able to run db.getCollection('collection').find({"_id": "user1"},{data:{$slice:[1,4]]} )
to get 4 elements from the data array from position 1.
How can I run the same query in golang
?
What I tried:
c.Find(bson.M{"_id":"user1" , "data":bson.M{"$slice":[]int{1,4}}} )
but i get "unknown operator $slice" Not sure what to do. Any help please?
Mongo Doc
{
"_id": "user1",
"time": 32467777,
"data": [
88,
45,
1,
4,
7,
123,
33,
132
]
}
The second argument you pass to MongoDB's find()
is a projection, for which the equivalent in mgo
is the Query.Select()
.
So you may do what you want like this:
var results bson.M
err := c.Find(
bson.M{"_id": "user1"},
).Select(
bson.M{"data": bson.M{"$slice": []int{1, 4}}},
).One(&results)
Also note that to query something exclusively by its ID, you may use the Collection.FindId()
, so you may write it more compact like this:
var results bson.M
err := c.FindId("user1").Select(
bson.M{"data": bson.M{"$slice": []int{1, 4}}},
).One(&results)