【问题标题】:Return the count of subcollection array with the result in MongoDB and sort with ascending返回子集合数组的计数以及 MongoDB 中的结果并按升序排序
【发布时间】:2017-03-12 16:23:29
【问题描述】:

我在获取子集合的计数时遇到问题,结果按升序帐户排序到计数。

这是我的收藏 scripts 的样子:

{
    "_id" : ObjectId("58bbf0a4b14e5fc44d5e9393"),
    "label" : "Binarization",
    "name" : "nlbin",
    "require" : []
},
{
    "_id" : ObjectId("58bbfb5eb14e5fc44d5e9c87"),
    "label" : "Binarization",
    "name" : "jpeg",
    "require" : [ObjectId("58bbf0a4b14e5fc44d5e9393")]
},
{
    "_id" : ObjectId("58bbfb4db14e5fc44d5e9c76"),
    "label" : "Binarization",
    "name" : "pseg",
    "require" : [ObjectId("58bbf0a4b14e5fc44d5e9393"), ObjectId("58bbfb5eb14e5fc44d5e9c87")]
}

所以问题是我想返回带有数组字段计数的集合require 也按升序对它们进行排序。我写的查询是这样的:

db.getCollection('scripts').aggregate({ $unwind: "$require" },{ $sortByCount:"$require" },{$sort: {count: 1}})

问题是它没有返回想要的结果,它实际上返回了这样的结果:

{
    "_id" : ObjectId("58bbf0a4b14e5fc44d5e9393"),
    "count" : 2
},

{
    "_id" : ObjectId("58bbfb5eb14e5fc44d5e9c87"),
    "count" : 1
}

这是完全错误的,因为ObjectId("58bbf0a4b14e5fc44d5e9393") 应该有计数0。此外,结果中甚至不包括具有最大 count(即 ObjectId("58bbfb4db14e5fc44d5e9c76"))的集合。

最终结果应该是这样的:

{
    "_id" : ObjectId("58bbf0a4b14e5fc44d5e9393"),
    "count" : 0
},

{
    "_id" : ObjectId("58bbfb5eb14e5fc44d5e9c87"),
    "count" : 1
},
{
    "_id" : ObjectId("58bbfb4db14e5fc44d5e9c76"),
    "count" : 2
}

希望你们明白我的意思

【问题讨论】:

    标签: mongodb sorting mongodb-query aggregation-framework


    【解决方案1】:

    您可以做的最好的事情是添加一个额外的字段(使用 $addFields)来保存 require 数组大小,而无需 $unwind 然后根据该字段对文档进行排序,例如

    db.getCollection('scripts').aggregate([
        { "$addFields": { "count": { "$size": "$require" } } },
        { "$sort": { "count": 1 } }
    ])
    

    【讨论】:

    • 感谢它的工作。这很好,我可以在我的聚合函数中制作像字段一样的投影。
    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    相关资源
    最近更新 更多