温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

mongodb查询案例,golang库mgo案例

发布时间:2020-02-14 11:09:13 来源:网络 阅读:730 作者:梁十八 栏目:MongoDB数据库
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))

等效于(查询id为1,只取出last_msg字段,不取_id,并将last_msg的数组取出展开,按last_msg.date逆序排列,跳过前2条,只选取2条):

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表结构:

mongodb查询案例,golang库mgo案例

其中一条数据:

{
    "_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": "你是不是在和别人..."
        }
    ]
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI