mongodb查詢案例,golang庫mgo案例

pipeline := []bson.M{
   bson.M{"$match": bson.M{"id": uid}},
   bson.M{"$project": bson.M{"last_msg": 1, "_id": 0}},
   bson.M{"$unwind": "$last_msg"},
   bson.M{"$sort": bson.M{"last_msg": -1}},
   bson.M{"$skip": 2},
   bson.M{"$limit": 2},
}
userModel := MongoDb.C("user")
pipe := userModel.Pipe(pipeline)
var data []interface{}
err := pipe.All(&data)
fmt.Println(data)
fmt.Println(len(data))

等效於

db.getCollection("user").aggregate([
    {$match: {"id":"1"}},
    {$project:{"last_msg":1, "_id":0}},
    {$unwind: "$last_msg"},
    {$sort: {"last_msg.date":-1}},
    {$skip:2},
    {$limit:2}
]);

mongodb表結構:

圖片.png

其中一條數據:

{
    "_id": ObjectId("5d2b24c16197934ef6db77ba"),
    "id": "1",
    "account": "你的女神",
    "passwd": "5d78eb174d633345054faf7d56a612ed",
    "friends": [
        {
            "uid": "2"
        },
        {
            "uid": "3"
        }
    ],
    "last_msg": [
        {
            "date": "1234567890",
            "from_id": "2",
            "msg": "在麼"
        },
        {
            "date": "1234567895",
            "from_id": "3",
            "msg": "女神"
        },
        {
            "date": "1234567898",
            "from_id": "4",
            "msg": "求你了,理理我好麼"
        },
        {
            "date": "1234567999",
            "from_id": "5",
            "msg": "你是不是在和別人..."
        }
    ]
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章