dongshen7407 2016-10-05 07:12
浏览 235
已采纳

筛选集合,但按内部属性排序

Considering that I have a collection of documents like below and I want to get information returned as follows:

Select all the entries from a campaign with campaignID = 12, sort by entries.questionscorrect in descending order with a limit of 10.

I have made a stab at a number of queries but I seem to be getting stuck on the fact that I am selecting on one level but want to order on a lower level i.e. property.

Here's what I have so far:

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

How can I write this in either Go (Mgo) syntax or straight MongoDB query please?

I keep getting returned information but sorted on the number of

{
    "_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条回答

  • duanhuai7532 2016-10-05 07:44
    关注

    Try below:

    db.getCollection('main').aggregate([
    {$match: {"campaignID" : 12.0}},
    {$unwind:"$entries"},
    {$sort: {"entries.questionscorrect": -1}},
    {$group:{_id:"$_id", 
        "entries":{$push:"$entries"}}}
    ])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建