过滤集合但对内部属性进行排序

时间:2016-10-05 07:12:34

标签: mongodb sorting go mgo

考虑到我有一些文件,如下所示,我想获得如下信息:

从包含campaignID = 12的广告系列中选择所有条目,按entries.questionscorrect降序排列,限制为10。

我已经对一些查询进行了尝试,但我似乎陷入了这样一个事实:我在一个级别上选择但是想要在较低级别(即财产)进行订购。

这是我到目前为止所拥有的:

db.getCollection('main').find({"id":4}, {"entries": 1}).sort({"questionscorrect": -1}).limit(2)

如何用Go(Mgo)语法或直接MongoDB查询来编写它?

我一直收到返回的信息,但按照

的数量排序
{
    "_id": ObjectId("57f4a590a4be269aa54a0505"),
    "campaignID": 12,
    "name": "name-here",
    "description": "description-here",
    "entries": [{
        "id": 1,
        "nickname": "conorh",
        "name": "conor h***",
        "email": "ch@gmail.com",
        "agreeTerms": true,
        "optInMarketing": false,
        "questionscnswered": 10,
        "questionscorrect": 3
    }, {
        "id": 2,
        "nickname": "bobs",
        "name": "bob smyth",
        "email": "bs12121@gmail.com",
        "agreeTerms": true,
        "optInMarketing": false,
        "questionscnswered": 10,
        "questionscorrect": 6
    }, {
        "id": 3,
        "nickname": "jd12",
        "name": "jane doe",
        "email": "janedough@gmail.com",
        "agreeTerms": true,
        "optInMarketing": false,
        "questionscnswered": 10,
        "questionscorrect": 1
    }]
}

1 个答案:

答案 0 :(得分:0)

尝试以下:

db.getCollection('main').aggregate([
{$match: {"campaignID" : 12.0}},
{$unwind:"$entries"},
{$sort: {"entries.questionscorrect": -1}},
{$group:{_id:"$_id", 
    "entries":{$push:"$entries"}}}
])