MongoDB排序不起作用

时间:2015-03-17 09:53:03

标签: mongodb sorting mongodb-query

从今天早上起(我想),我无法对我的收藏品进行排序。该系列里面有26944个物品(目前是我最大的物品 - 但这不是正确的原因吗?)。

所以我正在做的事情:

myCollection.find().sort({ _id: 1 })

这很好用,没有任何问题! 但是:

myCollection.find().sort({ xxx: 1 })

每个其他情况都不起作用,xxx表示我对象上的任何其他键无关紧要我... 例如:

myCollection.find({modified: { $exists : true } })

返回26944个对象的结果,

myCollection.find({modified: { $exists : true } }).sort({"modified":-1})

将返回0个对象。

我有什么不对吗? 也许我撞坏了我的收藏品?有人知道在这种情况下可以做些什么吗? (除了丢弃收藏品)

示例对象:

{
    "_id": ObjectId("55071e25760e250d050ed8d5"),
    "sysModified": new Date("2015-03-15T21:10:12+0100"),
    "created": new Date(1426529829922),
    "modified": new Date(1426528563945),
    "payments": [

    ],
    "orderItems": [
        {
            "orderId": 'xxxxx',
            "itemId": 'xxxxx',
            "ean": "XXXXX"
            "quantity": 1,
            "name": "xxxxxxx",
            "vat": 19,
            "price": 29.989999999999998437,
            "currency": "EUR",
            "_id": ObjectId("5507365c89866d820dcef7e0"),
        },
        {
            "orderId": 'xxxxx',
            "itemId": 'xxxxx',
            "ean": "XXXXX"
            "quantity": 1,
            "name": "xxxxxxx",
            "vat": 19,
            "price": 29.989999999999998437,
            "currency": "EUR",
            "_id": ObjectId("5507365c89866d820dcef7e1"),
        }
    ],
    "orderData": {
        "orderId": XXXXXXXXX,
        "type": "order",
        "status": "XXXXXXXXX",
        "timestamp_php": XXXXXXXXX,
        "customer": XXXXXXXXX,
        ...
    },
    "orderDeliveryAddress": {
        "customer": xxxxxxxxxxx,
        "company": "",
        "additional": "",
        "firstName": "xxxxxxxxxxx",
        "surname": "xxxxxxxxxxx",
        "street": "xxxxxxxxxxx",
        "houseNumber": "xxxxxxxxxxx",
        "zip": "xxxxxxxxxxx",
        "city": "xxxxxxxxxxx",
        "iso2": "xxxxxxxxxxx",
        "phone": "xxxxxxxxxxx",
        "fax": "xxxxxxxxxx",
        "email": "xxxxxxxxxxx",
    },
    "orderCustomerAddress": {
        "customer": xxxxxxxxxxx,
        "company": "",
        "additional": "",
        "firstName": "xxxxxxxxxxx",
        "surname": "xxxxxxxxxxx",
        "street": "xxxxxxxxxxx",
        "houseNumber": "xxxxxxxxxxx",
        "zip": "xxxxxxxxxxx",
        "city": "xxxxxxxxxxx",
        "iso2": "xxxxxxxxxxx",
        "phone": "xxxxxxxxxxx",
        "fax": "xxxxxxxxxx",
        "email": "xxxxxxxxxxx",
    },
    "__v": 1
}

1 个答案:

答案 0 :(得分:0)

可能会使您的收藏变得更大。如果您尝试对键进行排序,那么没有索引,如果结果集很大,则会导致错误。错误应如下所示:

error: {
        "$err" : "too much data for sort() with no index.  
                  add an index or specify a smaller limit",
        "code" : 10128
}

您可以执行的操作是为要排序的键添加索引:

db.myCollection.ensureIndex({"modified":-1})

或者在排序之前减少结果集:

myCollection.find({modified: { $exists : true } }).limit(10).sort({"modified":-1})