如何使用golang获取mongodb中数组中的最后一个元素?
I'm working in go language. I'm using mgo driver to get the data from mongodb. I want last entry from the events array.
There will be huge data in future. so I don't want to read the whole record but just want specific data from the record.
db.events.find({"_id":"59ce53b9-970a-44a2-8419-b41a99120b25"},{"events":{$slice:-1}}).pretty()
this is working in mongo shell. I want this to work in go lang.
This is the sample data, from which I want last entry present in events.
{
"_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"version" : 9,
"events" : [
{
"event_type" : "customer:added",
"data" : {
"id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"name" : "arjun"
},
"timestamp" : ISODate("2017-11-20T12:21:34.910Z"),
"aggregate_type" : "customer",
"_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"version" : 1
},
{
"event_type" : "customer:address-updated",
"data" : {
"id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"address" : "bangalore"
},
"timestamp" : ISODate("2017-11-20T12:22:08.496Z"),
"aggregate_type" : "customer",
"_id" : "59ce53b9-970a-44a2-8419-b41a99120b25",
"version" : 2
}
]
}
我正在使用Go语言。 我正在使用mgo驱动程序从mongodb获取数据。 我想要事件数组中的最后一个条目。 p>
将来会有大量数据。 因此,我不想读取整个记录,而只想从记录中读取特定数据。 p>
db.events.find({ “_ ID”: “59ce53b9-970a-44a2-8419-b41a99120b25”},{ “事件”:{$切片:-1} })。pretty() code> pre>这在mongo shell中有效。 我希望它可以在go lang中工作。 p>
这是示例数据,我希望从这些数据中出现事件。 p>
{ “ _id”:“ 59ce53b9-970a-44a2-8419-b41a99120b25”, “版本”:9, “事件”:[ { “ event_type”:“客户:已添加”, “数据”:{ “ id”:“ 59ce53b9-970a-44a2-8419-b41a99120b25”, “ name”:“ arjun” } , “ timestamp”:ISODate(“ 2017-11-20T12:21:34.910Z”), “ aggregate_type”:“ customer”, “ _id”:“ 59ce53b9-970a-44a2-8419-b41a99120b25” , “ version”:1 }, { “ event_type”:“ customer:address-updated”, “ data”:{ “ id”:“ 59ce53b9-970a-44a2-8419 -b41a99120b25“, ”地址“:”班加罗尔“ }, ”时间戳“:ISODate(” 2017-11-20T12:22:08.496Z“), ” aggregate_type“:”客户“,\ n“ _id”:“ 59ce53b9-970a-44a2-8419-b41a99120b25”, “版本”:2 } ] } code> pre> div>
What you pass as the 2nd argument to find()
is a projection.
Projections in mgo
can be specified using the Query.Select()
method.
So your query in mgo
simply looks like this:
sess := ... // Acquire MongoDB session
c := sess.DB("dbname").C("events")
var doc bson.M
err := c.FindId("59ce53b9-970a-44a2-8419-b41a99120b25").
Select(bson.M{"events": bson.M{"$slice": -1}}).
One(&doc)
if err != nil {
// Handle error
}
fmt.Println(len(doc["events"].([]interface{}))) // This prints 1
fmt.Println(doc)